[LeetCode][LintCode] Two Sum
思路:
这道题因为只有一对,所以可以用hashmap,需要注意的是,数字可能有重复, eg.[1,2,2,3,4] target = 4. 所以最好的办法就是把剩下的放进去。 这样如果有重复,没关系,把现在的index和已经放进去的index返回即可。
class Solution { public int[] twoSum(int[] nums, int target) { int[] rst = new int[2]; if (nums == null || nums.length < 2) { return rst; } Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int left = target - nums[i]; if (map.containsKey(nums[i])) { rst[0] = map.get(nums[i]); rst[1] = i; break; } map.put(left, i); } return rst; } }
posted on 2018-02-21 11:44 codingEskimo 阅读(98) 评论(0) 收藏 举报
浙公网安备 33010602011771号