标签:
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 iand j is at most k.
Array Hash Table
这道题我采用的是map哈希表来做的,在这道题中,采用哈希表来记录已近遍历过的数,
题目需要求的是在这个数组中是否存在两个相同的数,他们之间的距离小于k
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<utility>
using namespace std;
#define TRUE 1
#define FALSE 0
bool containsNearbyDuplicate(vector<int>& nums, int k){
if(nums.empty()||nums.size()==1)
return FALSE;
int len=nums.size();
map<int,int> ma;
ma.insert(map<int,int>::value_type(nums[0],0));
for(int i=1;i<len;i++)
{
int si=ma.count(nums[i]);
if(si==1)
{
map<int,int>::iterator iter=ma.find(nums[i]);
int i1=iter->second;
if(i-i1<=k)
return TRUE;
ma.erase(iter);
}
ma.insert(map<int,int>::value_type(nums[i],i));
}
return FALSE;
}
int main()
{
int ary[10]={1,0,1,1};
vector<int> nums(ary,ary+4);
cout<<containsNearbyDuplicate(nums,1)<<endl;
}
leetcode_219题——Contains Duplicate II(哈希表)
标签:
原文地址:http://www.cnblogs.com/yanliang12138/p/4622570.html