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
Have you met this question in a real interview?
Yes
No
这道题我采用的是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; }
时间: 2024-10-26 02:52:42