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
最新推荐文章于 2025-03-16 14:14:45 发布
本文介绍了一个针对LintCode上2Sum问题的解决方案。该方案通过使用HashMap实现了O(n)的时间复杂度来查找目标值对应的两个数在数组中的位置。文章详细展示了如何通过一次遍历填充HashMap,并在第二次遍历中验证是否存在符合条件的另一数。
712

被折叠的 条评论
为什么被折叠?



