标签:return targe length turn twosum inpu 情况 sum ++
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
标签:return targe length turn twosum inpu 情况 sum ++
原文地址:http://www.cnblogs.com/bloomingFlower/p/6799647.html