LeetCode 167. sum of two numbers input ordered array Ⅱ

Given an ordered array is sorted in ascending order according to find the two numbers such that their sum is equal to the sum of the target number. 

Function should return the two index values and index1 index2, which must be less than index1 index2. 

Description: 

Returns the index value (index1, index2 and) is not zero. 
You can assume that each input corresponding to only the only answer, but you can not reuse the same elements. 
Example: 

Input: Numbers = [2, 7,. 11, 15], target = 9 
Output: [ 1,2 ] 
Explanation: 2 and 7 is equal to the sum of the target number 9. Thus index1 = 1, index2 = 2.

Problem-solving ideas

1. Violence hit the table, time out

class Solution {
  public int[] twoSum(int[] numbers, int target) {
    for (int i = 0; i < numbers.length; i++) {
      for (int j = i + 1; j < numbers.length; j++) {
        if ((numbers[i] + numbers[j]) == target) {
          return new int[] {i+1, j+1};
        }
      }
    }
    throw new IllegalArgumentException("参数不存在!");
  }
}

2. Double pointer collision (the official solution)

class Solution {
  public int[] twoSum(int[] numbers, int target) {
    int left = 0;
    int right = numbers.length - 1;
    while (left < right) {
      if ((numbers[left] + numbers[right]) > target) { right--; } else if ((numbers[left] + numbers[right]) < target) { left++; } else { return new int[] {left + 1, right + 1}; } } throw new RuntimeException("找不到参数"); } }

Time complexity of O (n), the spatial complexity is O (1)

3. dichotomy (from comments), you need to specify the starting query position dichotomy boundary value is a little big pit

class Solution {
   public  int [] twoSum ( int [] Numbers, int target) {
     for ( int I = 0; I <numbers.length; I ++ ) {
       // find the target-numbers [i] in position by the two points, note boundary value
       // binary search should be left starting position i + 1, otherwise, for the test [1, 2, 3, 4, 4, 9, 56, 90] 8, will return to the situation [4,4] appears 
      int = binarySearch right (Numbers, I +. 1, numbers.length -. 1, target - Numbers [I]);
       IF (! right = -1 ) {
         return  new new  int [] {I +. 1, right +. 1 }; 
      } 
    } 
    the throw  new new IllegalArgumentException();
  }

  public int binarySearch(int nums[], int left, int right, int target) {
    while (left <= right) {
      int mid = (left + right) / 2;
      if (nums[mid] == target) {
        return mid;
      } else if (nums[mid] < target) {
        left = mid + 1;
      } else {
        right = mid - 1;
      }
    }
    return -1;
  }
}

Time complexity of O (n ^ 2), the spatial complexity is O (1)

Guess you like

Origin www.cnblogs.com/lz-0011/p/11409379.html