<>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
©2019-2020 Toolsou All rights reserved,
use css Design a simple style html login interface The industrial Internet may not be 5G My life-saving straw C/C++ Memory model Do you have a magic interview ? Half a month 25 College questions , Actually captured Ali P8offerJava Misunderstanding —— Method overloading is a manifestation of polymorphism ?springboot2 Separation of front and rear platforms ,token Put in header Pit for verification Regression of dependent variable order categories (R language )Pandas Fundamentals of statistical analysis _ data processing (DataFrame Common operations )Unity2019 UIElement note ( ten ) Simple exercise 2 45 The 12-year-old programmer was turned down , Is the workplace wrong ?