您的位置:首页 > 大数据 > 人工智能

leetcode_219题——Contains Duplicate II(哈希表)

2015-07-05 16:48 489 查看

Contains Duplicate II

Total Accepted: 13284 Total Submissions: 51898My Submissions
Question Solution

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.

Hide Tags
Array Hash Table

Have you met this question in a real interview?
Yes

No

Discuss

这道题我采用的是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;
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: