The title

LeetCode 167, sum of two numbers II – Enter ordered array associative type: array two-pointer binary lookup

Given an array of integers in ascending order numbers, find two numbers that add up to the target number. The function should return the subscript values of these two numbers as an array of integers of length 2. The subscript of numbers starts at 1, so the answer array should be 1 <= answer[0] < answer[1] <= numbers. Length. You can assume that each input corresponds to a unique answer, and you can't reuse the same elements. Example 1: Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 equals the target number 9. So index1 = 1, index2 = 2. Example 2: Input: numbers = [2,3,4] target = 6 Output: [1,3] Example 3: Input: numbers = [-1,0] Target = -1 Output: [1,2] Hint: 2 <= numbers. Length <= 3 * 104-1000 <= numbers[I] <= 1000 numbers in ascending order -1000 <= target <= 1000 Only one valid answer existsCopy the code

Time to solve the problem.

class Solution {
      public int[] twoSum(int[] numbers, int target) {
      
    
    }
}
Copy the code

The method input parameters are given above to complete the answer.

Subject analysis

  1. This problem can be solved using double Pointers
  2. One pointer is used to point backwards and one is used to point backwards
  3. A direct return that adds to target is encountered
  4. Otherwise, lower than target is low++ and higher than target is high–

Answers to analysis

This article only analysis I do the idea, only for reference, to understand a solution to the idea, other kinds of ideas to do the problem please access the Internet.

Answer successful: Execution time :1 ms, beat 93.61% of Java users memory consumption :38.8 MB, beat 32.80% of Java users

import java.util.HashMap; import java.util.Map; //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int[] twoSum(int[] numbers, int target) { int low = 0; int high = numbers.length - 1; while (low < high ) { if (numbers[low] + numbers[high] == target) { return new int[]{low + 1, high + 1}; } else if (numbers[low] + numbers[high] < target) { low++; } else { high--; } } return null; }}Copy the code