简体   繁体   中英

how i can optimize this java code?

In below code string is passed in a method with numbers separated by space, now we need to provide sum of smallest two numbers in the string.

public class SumNearZero {
public static int SumNearZero(String s) {
String temp=s;
int t1=0;
for (int i = 0; i <s.length(); i++) {

    if(temp.contains(" "))
    {
        t1++;
        temp=temp.substring(temp.indexOf(" ")+1);
    }
}
int a[]=new int[++t1];
int index=0;
for(int i=0; i<s.length(); i++)
{
if(s.contains(" "))
{
    a[index]=Integer.parseInt(s.substring(0,s.indexOf(" ")));
    s=s.substring(s.indexOf(" ")+1);
    index++;
}

}
a[index]=Integer.parseInt(s);

for (int i = 0; i < a.length; i++) {

for(int j=0; j<a.length-1; j++)
{
    int c=a[j],n=a[j+1];
    if(c>n)
    {
        int t=c;
        a[j]=n;
        a[j+1]=t;

    }   }   }
int result=a.length>1 ? a[0]+a[1]:a[0];
return result;
  }
public static void main(String[] args) {
System.out.println(SumNearZero("35 96 10 20 5"));
       }
         }

Above code is working fine but i want to reduce the code. if you provide some suggestion regarding this, I'll be happy to learn from you.

Restrictions : use of Collections, predefined methods eg(String.split(),Arrays.sort()...)

I would suggest you not perform your calculation and display in a constructor, create a static method and invoke it. Next, in that method, create a List of Integer by iterating the substrings generated by splitting your input on one (or more) white space characters. Then, sort the List . Finally, return the sum of the first two elements 1 . It's also a good to do some error checking for one number (or no numbers). That might look something like

public static int sumNearZero(String s) {
    List<Integer> al = new ArrayList<>();
    for (String str : s.split("\\s+")) {
        al.add(Integer.parseInt(str));
    }
    if (al.isEmpty()) {
        return 0;
    }
    Collections.sort(al);
    if (al.size() == 1) {
        return al.get(0);
    }
    return (al.get(0) + al.get(1));
}

Then invoke it like

public static void main(String[] args) {
    System.out.println(sumNearZero("35 96 10 20 5"));
}

I get (as I expected)

15

1 once sorted the first two are the minimum, and the last two are the maximum

You can make it faster by using for each loop instead of for loop every time, it is more recommended and faster approach whenever loop is increasing for array, lists etc.

Plus more you can get all numbers in string by using split function which retrives you array of those numbers.and then you can put your logic for getting small numbers.this will reduce counting and increase speed highly in general if you want to learn about optimization then this is definitive guide i suggest you to go through it. and see this answer.

Looks like an exercise, so not giving actual code.

Use String.split and Arrays.sort

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM