leetcode219. 存在重复元素 II

给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的绝对值最大为 k。

示例 1:
输入: nums = [1,2,3,1], k = 3
输出: true

示例 2:
输入: nums = [1,0,1,1], k = 1
输出: true

示例 3:
输入: nums = [1,2,3,1,2,3], k = 2
输出: false

思路:用一个map来存储当前的值和它的索引,当我们遍历到和某个值时,如果当前的map包含这个值就进行索引相减,得到的结果要是小于或等于k,说明找到便可以返回true了,如果一直没有找到map中的值或者索引相减的结果大于k,则最后返回false;

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        int nCount = nums.size();
        map<int,int> mapMatchIndex;
        for(int i=0;i<nCount;i++)
        {
            if(mapMatchIndex.find(nums[i]) != mapMatchIndex.end() && i - mapMatchIndex[nums[i]] <= k)
                return true;
            else
            {
                mapMatchIndex[nums[i]] = i;
            }
        }
        return false;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43498985/article/details/86247006
今日推荐