"Description Given an array of integers and an integer k , find out whether there are two distinct indices i and j n the array such that nums[i] = nums[j] and th .."

[每日 LeetCode] 219. Contains Duplicate II

Description

Given an array of integers and an integer k , find out whether there are two distinct indices i and j n the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

Example 1:

Input: nums = [1,2,3,1], k = 3
Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1
Output: true

Example 3:

Input: nums = [1,2,3,1,2,3], k = 2
Output: false

思路:本题是寻找数组中是否存在重复元素的升级版,在原题上需继续判断相等元素下标的差不能大于 k。考虑使用 map 数据结构,数组元素映射为 key,数组下标映射为 value,遍历数组,如果不存在相等元素就更新到 map 中,直到遍历完数组。


C++ 代码

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        if (nums.size() < 2 || k < 1) return false;
        unordered_map<int, int> numsMap;
        for (int i = 0; i < nums.size(); ++i)
        {
            if (numsMap.count(nums[i]) == true)
            {
                if (i - numsMap[nums[i]] <= k)
                    return true;
                else numsMap[nums[i]] = i;
            }
            numsMap.insert(pair<int, int>(nums[i], i));
        }
        return false;
    }
};

运行时间:32ms 运行内存:15.4M

  • LeetCode

    LeetCode(力扣)是一个全球极客挚爱的高质量技术成长平台,想要学习和提升专业能力从这里开始,充足技术干货等你来啃,轻松拿下 Dream Offer!

    122 引用 • 34 回帖
  • array
    45 引用 • 2 回帖
  • Easy
    74 引用 • 10 回帖
感谢    关注    收藏    赞同    反对    举报    分享
回帖    
请输入回帖内容...