给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例
给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
思路
我希望通过O(n)的时间复杂度完成要求。第一遍O(n)的算法将每个数据a对应的target-a建立查询的数据结构,例如Hash表;第二遍遍历时,查询每个数是否在Hash表中,每次查询时间复杂度为O(1),总的时间复杂度是O(n)。代码
class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) map.put(nums[i], i); for (int i = 0; i < nums.length; i++) { int value = target - nums[i]; //差值存在哈希表中且角标不是当前被减数自己 防止 6-3=3这种的清空的出现 if (map.containsKey(value) && map.get(value) != i) { int index = map.get(value); if (i < index) return new int[]{i, index}; return new int[]{index, i}; } } return new int[0]; } }
417

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



