32ms hash_map c++ solution


  • 0
    A
    class Solution {
        public:
            bool containsNearbyDuplicate(vector<int>& nums, int k) {
                std::unordered_map<int, int> hash;
                std::vector<int>::iterator it;
                std::unordered_map<int, int>::iterator it_map;
                int counter = 0;
                for (it = nums.begin(); it != nums.end(); it++, counter++) {
                    it_map = hash.find(*it);
                    if (it_map != hash.end()) {
                        if (counter - hash[*it] <= k) {
                            return 1;
                        }
                    }
                    hash[*it] = counter;
                }
                return 0;
            }
        };

  • 1
    C

    Rather less verbose version of the same.

    #include <unordered_map>
    using namespace std;
    
    class Solution {
        public: 
            bool containsNearbyDuplicate(vector<int>& nums, int k) {
                unordered_map<int, int> hash;
                for (int i= 0; i< nums.size(); ++i) {
    	            auto it = hash.find(nums[i]);
    	            if (it!= hash.end() && i-it->second <= k)
    		            return true;
    	            else
    		            hash[nums[i]]= i;
    	        }
                return false;
    	    }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.