###### tags: `LeetCode` `Easy` # LeetCode #219 [Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii) ### (Easy) 給定一個整數數組和一個整數 k,判斷數組中是否存在兩個不同的索引 i 和 j,使得 nums [i] = nums [j],並且 i 和 j 的差的 絕對值 至多為 k。 --- 利用unordered_map存值與對應的位置, 每次遇到重複值就比對這次的位置與上一個出現的位置的差是否小於等於k。 --- ``` class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { unordered_map<int,int> bucket; for(int i=0;i<nums.size();i++){ if(bucket.find(nums[i])!=bucket.end()) if(i-bucket[nums[i]]<=k)return 1; bucket[nums[i]]=i; } return 0; } }; ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up