LeetCode 219 Contains Duplicate II

时间:2021-07-30 16:31:50

Problem:

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 j is at most k.

Summary:

给出数组nums,整型数k,找到数组中是否存在nums[i]和nums[j]相等且i - j小于k的情况。

Solution:

开始用最简单写法,两重for循环逐一查找,出现TLE。

后用HashMap改进,key为数组中出现的数字,value为最近出现位置的下标。

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