public class Solution {
/*
* @param numbers : An array of Integer
* @param target : target = numbers[index1] + numbers[index2]
* @return : [index1 + 1, index2 + 1] (index1 < index2)
*/
public int[] twoSum(int[] numbers, int target) {
// 2015-09-25 O(n)时间
if (numbers == null || numbers.length == 0) {
return new int[2];
}
int[] rst = new int[2];
HashMap<Integer, Integer> map = new HashMap<>();
int count = 1;
for (int i = 0; i < numbers.length; i++) {
map.put(numbers[i], count++);
}
for (Integer temp : map.keySet()) {
if (map.containsKey(target - temp)
&& map.get(temp) != map.get(target - temp)) {
rst[0] = Math.min(map.get(temp), map.get(target - temp));
rst[1] = Math.max(map.get(temp), map.get(target - temp));
return rst;
}
}
return new int[2];
}
}
[刷题]2 Sum
最新推荐文章于 2024-01-29 09:04:54 发布