<>167. Sum of two numbers II - Input ordered array

<> Given one is in ascending order Ordered array of , Find two numbers so that their sum equals the target number .

<> The function should return these two subscript values index1 and index2, among index1 Must be less than index2.

<> explain :

<> The returned subscript value （index1 and index2） It's not starting from scratch .

<> You can assume that each input corresponds to only one answer , And you can't reuse the same elements .

<> Examples :

<> input : numbers = [2, 7, 11, 15], target = 9

<> output : [1,2]

<> explain : 2 And 7 The sum is equal to the target number 9 . therefore index1 = 1, index2 = 2 .

<> Method 1 ： The double loop judges whether it is equal one by one , Get the corresponding index .
public static int[] twoSum(int[] numbers, int target) { int[] index = new int[2
]; for (int i = 0; i < numbers.length; i++) { for (int j = i + 1; j < numbers.
length; j++) { if (numbers[i]+numbers[j]==target){ index[0] = i+1; index[1] = j+
1; } } } return index; }
<> Method 2 ： Double pointer , According to the sum result and the size of the target value to determine whether the index is forward or backward
public static int[] twoSum(int[] numbers, int target) { // Double pointer int left = 0;
int right = numbers.length - 1; while (left < right) { int sum = numbers[left] +
numbers[right]; if (sum == target) { return new int[]{left + 1, right + 1}; }
else if (sum > target) { right--; } else { left++; } } return new int[2]; }

Technology
Daily Recommendation
views 2