Leetcode 219. Contains Duplicate II (Easy) (cpp)

来源:互联网 发布:nginx php 空白 编辑:程序博客网 时间:2024/06/07 00:09

Leetcode 219. Contains Duplicate II (Easy) (cpp)

Tag: Array, Hash Table

Difficulty: Easy


/*219. Contains Duplicate II (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.*/class Solution {public:    bool containsNearbyDuplicate(vector<int>& nums, int k) {        if (nums.size() < 2 || k < 1) {            return false;        }        unordered_map<int, int> mapping;        for (int i = 0; i < nums.size(); ++i) {            if (mapping.count(nums[i]) && i - mapping[nums[i]] <= k) {                return true;            }            mapping[nums[i]] = i;        }        return false;    }};


0 0
原创粉丝点击