原文题目:
读题:
217只要找出是否有重复值,
219找出重复值,且要判断两者索引之差是否小于k
//217. Contains Duplicate 46ms
class Solution
{
public:
bool containsDuplicate(vector<int>& nums)
{
set <int> s;
//vector <int>::iterator it;
int i = 0;
if(nums.empty())
{
return false;
}
s.insert(nums[0]);
for(i = 1;i < nums.size();++i)
{
if(s.count(nums[i]))
{
return true;
}
s.insert(nums[i]);
}
return false;
}
}; //217. Contains Duplicate 29ms
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
std::sort(nums.begin(), nums.end());
int i = 0, j = nums.size() - 1;
while (i < j) {
if (nums[i] == nums[i+1])
return true;
++i;
}
return false;
}
}; //219. Contains Duplicate II 25ms
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map <int, int> m; //如果用的是map,那么时间复杂度为35ms
for (int i = 0; i < nums.size(); ++i)
{
if (m.find(nums[i]) != m.end() && i - m[nums[i]] <= k) return true;
else m[nums[i]] = i;
}
return false;
}
};