首页 > 其他 > 详细

167. Two Sum II - Input array is sorted

时间:2017-05-03 00:36:23      阅读:293      评论:0      收藏:0      [点我收藏+]

public class Solution {
public int[] twoSum(int[] numbers, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int[] results = new int[2];
for (int i = 0; i < numbers.length; i++) {
map.put(numbers[i], i);
if(map.containsKey(target - numbers[i])) {
results[0] = map.get(target - numbers[i])+1;
results[1] = i + 1;
return results;
}
}
return results;
}
}

_________________________________________________

map.put(numbers[i], i);

放在if循环之前可能出现数组中某个元素两倍等于target的情况,最后输出的result出错

public class Solution {
public int[] twoSum(int[] numbers, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int[] results = new int[2];
for (int i = 0; i < numbers.length; i++) {

if(map.containsKey(target - numbers[i])) {
results[0] = map.get(target - numbers[i])+1;
results[1] = i + 1;
return results;
}

map.put(numbers[i], i+1);
}
return results;
}
}

167. Two Sum II - Input array is sorted

原文:http://www.cnblogs.com/bloomingFlower/p/6799647.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!