LeetCode 219: Contains Duplicate II

219. Contains Duplicate II

Difficulty: Easy
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.

思路

217题Contains Duplicate中,使用了unordered_set容器。
在本题中,不仅要记录元素的值,还要记录元素在nums中的下标。因此,使用unordered_map容器。
同样,顺序遍历nums中元素,调用find判断map容器中是否存在该元素;
不存在则给map添加键-值元素对,键为该元素值,值为该元素的下标值;
存在,则还需判断目前的下标值与容器中存储的下标值是否差值不大于k;
不大于k,就直接返回true;大于就继续遍历nums。

代码

[C++]

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_map<int, int> mymap;
        int i = 0;
        for (vector<int>::iterator it = nums.begin(); it != nums.end(); ++it, ++i) {
            if (mymap.find(*it) != mymap.end()) {
                if (i - mymap[*it] <= k)
                    return true;
            }
            mymap[*it] = i;
        }
        return false;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值