167. Two Sum II - Input array is sorted

Posted bloomingFlower

tags:

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

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的主要内容,如果未能解决你的问题,请参考以下文章

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