leetcode Contains Duplicate II

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 difference between i and j is at most k

这道题自己最后没有做出来,看的是【陆草纯】的解法。

如果是JAVA的hashmap的话很简单,但是C++没有,之前我也想过用map按值排序,半天实现不了。

先讲一下陆草纯的解法:

构建一个map,如果nums里的元素在map里没有出现过的话,就先保存下标。

如果出现过的话,就比较一下下标差值是否小于k。然后更新下标(每次都储存每个元素的最新下标)

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_map<int,int> vec;
        int s=nums.size();
        if(s==0||k==0) return false;
        for(int i=0;i<s;i++){
            if(vec.find(nums[i])==vec.end()){
                vec[nums[i]]=i;
            }
            else {
                if(i-vec[nums[i]]<=k) return true;
                vec[nums[i]]=i;
            }
        }
        return false;
    }
};
原文地址:https://www.cnblogs.com/LUO77/p/5046501.html