LeetCode01 两数之和
01
java中,HashMap的containsKey查找非常快,时间复杂度是O(1)
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
int key = target - nums[i];
if (map.containsKey(key)) {
return new int[] {i, map.get(key)};
} else {
// 你可以假设每种输入只会对应一个答案,所以这里不用担心已经存在key而更新了value
map.put(nums[i], i);
}
}
return null;
}

浙公网安备 33010602011771号