Given an array of integers and a target value, find two numbers in the array that sum to the target value.

the standard answer given by LeetCode when traversing the double-layer loop method is as follows:

public int[] twoSum(int[] nums, int target) {
    for (int i = 0; i < nums.length; iPP) {
        for (int j = i + 1; j < nums.length; jPP) {
            if (nums[j] == target - nums[i]) {
                return new int[] { i, j };
            }
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}

I think the outermost nums.length needs to be changed to nums.length-1. If the array has four elements, then you can compare the whole process three times, which is the same as the outer loop of bubbling sorting.

What is the implied purpose of

or the standard answer?

look forward to your advice

Jun.18,2021

unnecessary, because the inner loop does not perform the final operation, because when ionomnums are not less than nums.length 1, the j=i+1 is no less than

.
Menu