167. Two Sum II - Input array is sorted

Posted warmland

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了167. Two Sum II - Input array is sorted相关的知识,希望对你有一定的参考价值。

其实我不知道这道题的point是什么…………

两种方法,hashmap/ two pointers

HashMap

 1     public int[] twoSum(int[] numbers, int target) {
 2         if(numbers.length == 0) {
 3             return null;
 4         }
 5         int[] res = new int[2];
 6         Map<Integer, Integer> map = new HashMap<Integer, Integer>();
 7         for(int i = 0; i < numbers.length; i++) {
 8             if(!map.containsKey(target - numbers[i])) {
 9                 map.put(numbers[i], i);
10             } else {
11                 res[0] = map.get(target - numbers[i]) + 1;
12                 res[1] = i + 1;
13                 return res;
14             }
15         }
16         return res;
17     }

 

 

 

Two pointers

 1     public int[] twoSum(int[] numbers, int target) {
 2         if(numbers.length == 0) {
 3             return null;
 4         }
 5         int[] res = new int[2];
 6         int walker = 0;
 7         int runner = numbers.length - 1;
 8         int sum = numbers[walker] + numbers[runner];
 9         while(sum != target) {
10             if(sum > target) {
11                 runner--;
12             } else {
13                 walker++;
14             }
15             sum = numbers[walker] + numbers[runner];
16         } 
17         res[0] = walker + 1;
18         res[1] = runner + 1;
19         return res;
20     }

 

以上是关于167. Two Sum II - Input array is sorted的主要内容,如果未能解决你的问题,请参考以下文章

167. Two Sum II - Input array is sorted

167. Two Sum II - Input array is sortedeasy

167. Two Sum II - Input array is sorted

LeetCode167. Two Sum II - Input array is sorted

167. Two Sum II - Input array is sorted

167.Two Sum II–Input is sorted