码迷,mamicode.com
首页 > 其他好文 > 详细

167. Two Sum II - Input array is sorted

时间:2016-06-30 06:30:06      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

其实我不知道这道题的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

标签:

原文地址:http://www.cnblogs.com/warmland/p/5628753.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!