-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontainsNearbyDuplicate.cpp
More file actions
57 lines (50 loc) · 1.39 KB
/
containsNearbyDuplicate.cpp
File metadata and controls
57 lines (50 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
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 difference between i and jis at most k.
*/
//my Solution
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
map<int,int> mii;
vector<int> vi,anoVi;
for(auto x:nums)
mii[x]++;
for(auto x:mii)
{
if(x.second>1)
{
vi.clear();
anoVi.clear();
for(int i=0;i!=nums.size();i++)
{
if(x.first==nums[i])
vi.push_back(i);
}
for(auto it=vi.begin();it!=vi.end()-1;it++)
anoVi.push_back(*(it+1)-(*it));
sort(anoVi.begin(),anoVi.end());
if(anoVi[0]<=k)
return true;
}
}
return false;
}
};
//another
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k)
{
unordered_set<int> s;
if (k <= 0) return false;
if (k >= nums.size()) k = nums.size() - 1;
for (int i = 0; i < nums.size(); i++)
{
if (i > k) s.erase(nums[i - k - 1]);
if (s.find(nums[i]) != s.end()) return true;
s.insert(nums[i]);
}
return false;
}
};