原题:
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3 Output: trueExample 2:
Input: nums = [1,0,1,1], k = 1 Output: trueExample 3:
Input: nums = [1,2,3,1,2,3], k = 2 Output: false
这个和上一个题相比麻烦就麻烦在要存储这个数上一次出现的位置,为此不得不看了看map的用法,结果:
Success
Runtime: 28 ms, faster than 93.62% of C++ online submissions for Contains Duplicate II.
Memory Usage: 15.4 MB, less than 24.76% of C++ online submissions for Contains Duplicate II.
代码:
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int,int> lib;
for(int i=0;i<nums.size();i++){
if(lib[nums[i]]&&i-lib[nums[i]]<k){return true;}
lib[nums[i]]=i+1;
}
return false;
}
};
这次终于偷偷发现一个牛逼的结果,在details里找到的,手打的hash,给大家参考一下:
Success
Runtime: 20 ms, faster than 99.48% of C++ online submissions for Contains Duplicate II.
Memory Usage: 11.4 MB, less than 95.24% of C++ online submissions for Contains Duplicate II.
#define HASHSIZE 10009
#define NUMSIZE 100009
int hashTable[HASHSIZE];
long long getHash(long long n){
if (n < 0) n = -n;
return n% HASHSIZE;
}
struct node{
int value;
int next;
};
struct node arr[NUMSIZE];
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
int len = nums.size();
int i,j,key;
for (i = 0; i < HASHSIZE; i++)
hashTable[i] = -1;
for (i = 0; i < len; i++){
key = getHash((long long)nums[i]);
if (hashTable[key] < 0){
hashTable[key] = i;
arr[i].value = nums[i];
arr[i].next = -1;
}
else{
j = hashTable[key];
while (j >= 0){
if (nums[i] == arr[j].value && abs(i - j) <= k) return true;
j = arr[j].next;
}
arr[i].next = hashTable[key];
arr[i].value = nums[i];
hashTable[key] = i;
}
}
return false;
}
};