Given an array of integers and an integer k, find out whether there 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.
直接使用循环时间复杂度为O(N*k),使用stl中的基于红黑树实现的map能减少循环的时间,在O(logN)的时间复杂度内找到元素,或者更进一步使用基于hash表的unordered_map,在常数时间内找到元素。这道题学习到的两个经验:
- 当想在常数时间内完成查询工作时考虑hash表。
- stl中有用hash表实现的数据结构map和set,所以它们也保留了hash表查询上的特点。
代码如下:
class Solution {
public:
/* 解法一:超时
bool containsNearbyDuplicate(vector<int>& nums, int k) {
int length=nums.size();
if(length<=1||k<=0) return false;
//将每一个元素与其后面k个元素进行比较
for(int i=0;i<length;i++)
{
for(int j=1;j<=k&&(i+j)<length;j++)
{
if(nums[i]==nums[i+j])
return true;
}
}
return false;
}
*/
//解法二,利用stl中的map,记录下整数以及它的下标
bool containsNearbyDuplicate(vector<int>& nums, int k)
{
//之前直接使用的是map,时间是96ms,后来把map替换成unordered_map时间变成了32ms
unordered_map<int ,int> maps;
int length=nums.size();
for(int i=0;i<length;i++)
{
if(maps.count(nums[i]))//如果在maps中找到了该元素,判断它们位置是否小于等于k
{
if((i-maps[nums[i]])<=k)
return true;
}
maps[nums[i]]=i;
}
return false;
}
};