LeetCode # Array # Easy # 167. Two Sum II - Input array is sorted

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

Question: Given a sorted array, and a target value. It is required to find two numbers in the array whose sum is the target value, and give the index. Note that the index does not start at 0, but at 1.

Note: Assuming that there must be a set of numbers in the array that meet the requirements, each element is used only once.

Idea: When the target value is 0, return {1,2} directly. According to the meaning of the question, there must be two 0 elements, and they are sorted at the top of the array.

  Then use a for loop to jump out after finding two indices.

1  class Solution {
 2      public  int [] twoSum( int [] numbers, int target) {
 3           int [] index = {1,2 };
 4           int t2 = 0 ;
 5          if (target == 0 ){//direct return {1,2}
 6               return index;
 7           }
 8           for ( int i = 0; i< numbers.length; i++ ){
 9               boolean k = false ;
 10              if (numbers[i] != 0 ){ //current If the value is not 0, enter the inner loop                
 11                  index[0] =i+1 ; 
 12                    t2 = target - numbers[i];
 13                    for ( int j = i+1; j<numbers.length; j++ ){
 14                        if (numbers[j]== t2){
 15                            index[1]= j+1 ;
 16                            k= true ; // used to control the outer loop to jump out;
 17                            break ;
 18                        }                  
 19                    }
 20                    if (k == true ){ 
 21                        break ;
 22                   }
23              }
24          }
25          return index; 
26     }
27 }

Although this plan was changed step by step by myself, I am very excited. However, it was found that the time was poor, only exceeding 18% of the submits. It can be seen that my scheme is 0(n 2 ).

Refer to the best solution for improvement, Java solution - 0ms, beat 100%  .

The idea of ​​this method is to use binary search. I call the smaller index value of the two elements as a decimal, and the larger one as a large number.

If the sum of the elements at the beginning and end of the array is greater than the target value, it means that the value at the end is larger and should be reduced. So, use dichotomy to find a suitable large number.

If the sum of the first and last elements of the array is less than the target value, it means that the value of the first part is small and should be increased. So, look for a suitable decimal.

1  class Solution {
 2      public  int [] twoSum( int [] numbers, int target) {
 3         int l = 0, h = numbers.length - 1 , sum;
 4          while ((sum = numbers[l] + numbers[h ]) != target && h != l) {
 5              if (sum > target)
 6                  h = binarySearch(numbers, l + 1, h - 1, target - numbers[l]);//Find a suitable large number
 7              else  if (sum < target)
 8                  l = binarySearch(numbers, l + 1, h - 1 , target - numbers[h]);//Find a suitable decimal
 9         }                
10         return new int[]{l + 1, h + 1};
11     }
12 
13   private int binarySearch(int[] numbers, int low, int high, int target) {
14         while (low < high) {
15             int mid = (low + high) / 2;                        
16             if (target == numbers[mid]) {
17                 return mid;
18             } else if (target < numbers[mid]) {
19                 high = mid;
20             } else
21                 low = mid + 1;
22         }
23         return high;
24     }
25 }

It can be seen that the scheme is 0(nlogn). The dichotomy is really important.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325363752&siteId=291194637