Hash Table

1. Two Sum

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> hashtable;
        for (int i = 0; i < nums.size(); ++i) {
            int res = target - nums[i];
            if (hashtable.count(res) == 0){
              hashtable[nums[i]] = i;  
            } 
            else {
                return {i, hashtable[res]};
            }
        }
        return {-1, -1};
    }
};

219. Contains Duplicate II

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_map<int, int> hashmap;
        for (int i = 0; i < nums.size(); ++i) {
            if(hashmap.count(nums[i]) != 0) {
                int ind = i - hashmap[nums[i]];
                if (ind <= k) return true;
                else hashmap[nums[i]] = i;
            }
            else hashmap[nums[i]] = i;
        }
        return false;
    }
};









		
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s