您的位置:首页 > 大数据 > 人工智能

[LeetCode] Contains Duplicate II

2015-06-02 23:18 507 查看
Well, the basic idea is fairly straightforward. We maintain a mapping
mp
from a value in
nums
to its position (index)
i
. Each time we meet an unseen value, we add it to the map (
mp[nums[i]] = i
). Otherwise, depending on whether the recorded index
mp[nums[i]]
and the current index
i
satisfy
i - mp[nums[i]] <= k
(node that the new index
i
is larger than the old index
mp[nums[i]]
), we return
true
or update the index (
mp[nums[i]] = i
). If all the elements have been visited and we have not returned
true
, we will return
false
.

bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> mp;
for (int i = 0; i < nums.size(); i++) {
if (mp.find(nums[i]) != mp.end() && i - mp[nums[i]] <= k)
return true;
mp[nums[i]] = i;
}
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: