给你一个整数数组 nums 和一个整数 k ,判断数组中是否存在两个 不同的索引 i 和 j ,满足 nums[i] == nums[j] 且 abs(i - j) <= k 。如果存在,返回 true ;否则,返回 false 。
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> dictionary;
for (int i = 0; i < nums.size(); i++) {
int num = nums[i];
if (dictionary.count(num) && i - dictionary[num] <= k) {
return true;
}
dictionary[num] = i;
}
return false;
}
};
思路:从左到右遍历数组,如果当前元素哈希表里没有||有该元素但不符合abs(i-j)<=k的条件的时候,更新哈希表中num值的下标,若存在该元素且满足下标条件则返回true
unordered_map::count()是C++中的内置方法,用于通过给定 key 对unordered_map中存在的元素数量进行计数。
注意:由于unordered_map不允许存储具有重复键的元素,因此count()函数本质上检查unordered_map中是否存在具有给定键的元素。
用法:
size_type count(Key);
参数:此函数接受单个参数 key ,需要在给定的unordered_map容器中进行检查。
返回值:如果Map中存在具有给定键的值,则此函数返回1,否则返回0。
以下示例程序旨在说明unordered_map::count()函数:
// C++ program to illustrate the
// unordered_map::count() function
#include<iostream>
#include<unordered_map>
using namespace std;
int main()
{
// unordered map
unordered_map<int , string> umap;
// Inserting elements into the map
umap.insert(make_pair(1,"Welcome"));
umap.insert(make_pair(2,"to"));
umap.insert(make_pair(3,"GeeksforGeeks"));
// Check if element with key 1 is present using
// count() function
if(umap.count(1))
{
cout<<"Element Found"<<endl;
}
else
{
cout<<"Element Not Found"<<endl;
}
return 0;
}
输出:
Element Found