Friday, September 4, 2015

Leetcode: Contains Duplicate II (hash table)

PROBLEM:

https://leetcode.com/problems/contains-duplicate/

Using map and need to keep a windom with the maximal length of k.

//////////////////////////////////////////
//code

class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
if (k == 0 || nums.size() == 0)return false;
unordered_map<int, int> tmp;

//check the input
int pre = 0;
if (nums.size() == 0)return false;
for (int i = 0; i<nums.size(); i++){
tmp[nums[i]] = i;
if (pre == tmp.size())return true;
else pre = tmp.size();
//remove the first item from map
if (tmp.size() == k + 1){
tmp.erase(tmp.begin());
pre--;
}

}
return false;
}
};


No comments:

Post a Comment