leetCode 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.

Note:

  • Your returned answers (both index1 and index2) are not zero-based.
  • You may assume that each input would have exactly one solution and you may not use the sameelement twice.

Example:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

 1 class Solution5 {
 2 //  对于有序的数组这种方法会快很多
 3     /*
 4     这种方法的合理性:
 5         假设numbers[low']+numbers[high'] = target    -------①
 6         对于有序的整数数组,low只能++,high只能--,总会出现low走到low',或者high走到high'的情况。
 7         情况一:
 8             low先走到low':此时numbers[low]+numbers[high] > target, 只有high会移动,而low不变。一直等到①式成立为止。
 9         情况二:
10             high先走到high':此时numbers[low]+numbers[high] < target, 只有low会移动,而high不变。一直等到①式成立为止。
11 
12      */
13     public int[] twoSum(int[] numbers, int target) {
14         int[] result = new int[2];
15         int low = 0, high = numbers.length - 1;
16         while (low < high){
17             int sum = numbers[low] + numbers[high];
18             System.out.println(numbers[low] + "+"+numbers[high]+" = "+sum);
19             if (sum > target){
20                 --high;
21             }else if (sum < target){
22                 ++low;
23             }else {
24                 return new int[]{low+1, high+1};
25             }
26         }
27         return result;
28     }
29 
30 //    普通方法,有序无序都可以
31     public int[] twoSum(int[] numbers, int target) {
32         int[] result = new int[2];
33         //key:查找的数字,value:该数字对应的位置
34         Map<Integer, Integer> map = new HashMap<>();
35         for (int i = numbers.length - 1; i >= 0; i--) {
36             /*
37             检验map中是否有和 i 位置的数的和为target的,有结束查找,没有将i位置的数及其位置存入map
38              */
39             Integer indiceOfAnother = map.get(target - numbers[i]);
40             if (indiceOfAnother == null){
41                 map.put(numbers[i],i);
42             }else {
43                 result[0] = i+1;
44                 result[1] = indiceOfAnother+1;
45                 return result;
46             }
47         }
48         return result;
49     }
50 }

 



posted @ 2019-05-20 11:22  赤云封天  阅读(83)  评论(0)    收藏  举报