Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The only difference is the nested for loop in the first one is assigned the value of i+1 instead of just +1(second one). Why is the first one considered better than the second one?

int[] nums = { 3, 2, 4 };
int target = 6;

for (int i = 0; i < nums.length; i++) {
    for (int j = i + 1; j < nums.length; j++) {
        int answer = nums[i]+nums[j];
        System.out.println(answer);//answer should be value of target
    }
}
int[] nums = { 3, 2, 4 };
int target = 6;

for (int i = 0; i < nums.length; i++ ) {
    for (int j = 1; j < nums.length; j++) {
        int answer = nums[i]+nums[j];
        System.out.println(answer);//answer should be value of target
    }
}
question from:https://stackoverflow.com/questions/66054112/what-makes-this-approach-better-than-this-one

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
210 views
Welcome To Ask or Share your Answers For Others

1 Answer

These two codes are don't seem accomplishing the same to me. however as you said in the comment I'm trying to figure out.

In terms of run time, in the first code, the nested for loop runs nums.length - (i+1) times. Here the best case scenario for nested for loop runs 0 times and for the worst case scenario runsnums.length - 1 times.

int[] nums = { 3, 2, 4 };
int target = 6;

for (int i = 0; i < nums.length; i++) {
    for (int j = i + 1; j < nums.length; j++) {
        int answer = nums[i]+nums[j];
        System.out.println(answer);//answer should be value of target
    }
}

On the other hand in the 2nd code the nested for loop runs nums.length times. Here the best case and worst case scenario for nested for loop are the same which is runs nums.length times.

int[] nums = { 3, 2, 4 };
int target = 6;

for (int i = 0; i < nums.length; i++ ) {
    for (int j = 1; j < nums.length; j++) {
        int answer = nums[i]+nums[j];
        System.out.println(answer);//answer should be value of target
    }
}

Therefore, Based on best and worst case scenario we can say that the first code is more efficient.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...