diff options
Diffstat (limited to 'other/contains_duplicate2.cpp')
-rw-r--r-- | other/contains_duplicate2.cpp | 24 |
1 files changed, 24 insertions, 0 deletions
diff --git a/other/contains_duplicate2.cpp b/other/contains_duplicate2.cpp new file mode 100644 index 0000000..9af7758 --- /dev/null +++ b/other/contains_duplicate2.cpp @@ -0,0 +1,24 @@ +#include "leetcode.h" + +class Solution { +public: + bool containsNearbyDuplicate(vector<int> &nums, int k) { + unordered_map<int, int> um; + for (int i = 0; i < nums.size(); i++) { + if (um.count(nums[i])) + if (abs(i - um[nums[i]]) <= k) + return true; + um[nums[i]] = i; + } + return false; + } +}; + +int main() { + Solution obj; + vector<int> nums = {1, 2, 3, 1}; + if (obj.containsNearbyDuplicate(nums, 3)) + cout << "true"; + else + cout << "false"; +} |