Contains-Duplicate-II
第74天。
今天的题目是Contains Duplicate II:
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
显然这道题目可以用两个循环去实现,但是这样会超时,效率不高。
这里是用Hash Table去做的,key存储nums[i],value存储i,这样我们用O(n)的时间就可以完成了。
1 | bool containsNearbyDuplicate(vector<int>& nums, int k) { |
dicuss中的做法是用unordered_set去做的。
1 | bool containsNearbyDuplicate(vector<int>& nums, int k) |