[每日LeetCode] 219. Contains Duplicate II

  |   0 评论   |   659 浏览

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

评论

发表评论