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

LeetCode之“散列表”:Contains Duplicate && Contains Duplicate II

2015-06-20 20:39 330 查看

  1. Contains Duplicate

  题目链接

  题目要求:

  Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

  代码如下:

class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_map<int, int> hashMap;
int sz = nums.size();
for(int i = 0; i < sz; i++)
hashMap[nums[i]]++;

unordered_map<int, int>::iterator itr = hashMap.begin();
for(; itr != hashMap.end(); itr++)
{
if(itr->second >= 2)
return true;
}

return false;
}
};


  2. Contains Duplicate II

  题目链接

  题目要求:

  Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i andj is at most k.

class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> hashMap;
int sz = nums.size();
for(int i = 0; i < sz; i++)
{
if(hashMap.find(nums[i]) != hashMap.end())
{
int j = hashMap[nums[i]];
if(i - j <= k)
return true;
else
hashMap[nums[i]] = i;
}
else
{
hashMap[nums[i]] = i;
}
}

return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: