[LeetCode219] There are duplicate elements II (hash table)

1. The topic

insert image description here

The idea and code

hash. mp[i]=jIndicates the subscript of the number i in the original array. It is enough to traverse the judgment once.
PS: unordered_mapThe mp.find(value)returned value is the key value corresponding to the value.

At the beginning of this submission, I found that the following method has 3 test cases that have not been passed. For example, in [1, 0, 1, 1] k = 1this case, it should return true if it is found to be correct, but such a method will only judge the 0th 1 and the second 1. The position (without judging the last two 1s) is caused by not updating the latest value of the value corresponding to the key in the hash table.

class Solution {
    
    
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
    
    
        //mp[i]=j表示数字i在原数组的下标
        unordered_map<int, int>mp;
        int temp;
        for(int i = 0; i < nums.size(); i++){
    
    
            //存在nums[i]为key的kv
            if(mp.count(nums[i])){
    
    
                temp = abs(mp[nums[i]] - i);
                if(temp <= k){
    
    
                    return true;
                }
            }else{
    
    //之前没有遍历过这个数字
                mp[nums[i]] = i;
            }
        }
        return false;
    }
};

Therefore, when judging the existence of the hash table nums[i], it also needs to be updated at the end, that is, adding it ifinside mp[nums[i]] = i;.

class Solution {
    
    
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
    
    
        //mp[i]=j表示数字i在原数组的下标
        unordered_map<int, int>mp;
        int temp;
        for(int i = 0; i < nums.size(); i++){
    
    
            //存在nums[i]为key的kv
            if(mp.count(nums[i])){
    
    
                temp = abs(mp[nums[i]] - i);
                if(temp <= k){
    
    
                    return true;
                }
                mp[nums[i]] = i;  //一开始漏了这句,因为要更新!!
            }else{
    
    //之前没有遍历过这个数字
                mp[nums[i]] = i;
            }
        }
        return false;
    }
};

insert image description here
Thanks to Liu Xiaocong for adding the python solution, enumerateafter obtaining the index and value, use the key of the dictionary dic to store the value, and the value to store the index, and traverse four lines of code at a time to get it:

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        dic = {
    
    }
        # dic的key为数值, value为索引
        for key, v in enumerate(nums):
            if v in dic and key - dic[v] <= k:
                return True
            dic[v] = key
        return False

Guess you like

Origin blog.csdn.net/qq_35812205/article/details/123314874