HashMap的時間複雜度問題(待續)
阿新 • • 發佈:2018-12-09
在leecode上做的第一道題,求兩數之和的方法, 兩數之和-from leecode 除了暴力迴圈法之外,給出的答案是這樣的
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
這個就要求HashMap的查詢操作複雜度是o(1),真的是這樣嗎?需要進一步學習一下。