-
Notifications
You must be signed in to change notification settings - Fork 0
/
contains-duplicate-ii.h
34 lines (26 loc) · 888 Bytes
/
contains-duplicate-ii.h
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
#ifndef CONTAINS_DUPLICATE_II_H_
#define CONTAINS_DUPLICATE_II_H_
#include <vector>
#include <unordered_set>
namespace solution {
bool containsNearbyDuplicate(std::vector<int>& nums, int k) {
// brute force
// Runtime: 16 ms, faster than 97.99% of C++ online submissions for Contains Duplicate II.
// Memory Usage: 16.1 MB, less than 93.43% of C++ online submissions for Contains Duplicate II.
//
if (k == 0) return false;
auto size = std::unordered_set<int>(nums.cbegin(), nums.cend()).size();
if (size == nums.size()) return false;
if (nums.size() <= k + 1)
return size < nums.size();
auto begin = nums.cbegin(), current = begin, end = nums.cend();
while (current + k != end) {
if (std::unordered_set<int>(current, current + k + 1).size() < k + 1) {
return true;
}
current++;
}
return false;
}
}
#endif // CONTAINS_DUPLICATE_II_H_