Skip to content

Latest commit

 

History

History
44 lines (37 loc) · 1.18 KB

219.contains_duplicate_ii.md

File metadata and controls

44 lines (37 loc) · 1.18 KB

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 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

新建一个map保存相同元素的索引值,然后比较相同元素索引值中相邻两个索引是否有满足条件的。

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_map<int, vector<int >> cnt;
        for(int i=0;i<nums.size();i++)
            cnt[nums[i]].push_back(i);
        for(auto c:cnt)
            if(c.second.size()>1)
            {
                for(int i=1;i<c.second.size();i++)
                    if(c.second[i]-c.second[i-1]<=k)
                        return true;
                    }
        return false;
    }
};

执行用时 :56 ms, 在所有 C++ 提交中击败了50.75%的用户
内存消耗 :22 MB, 在所有 C++ 提交中击败了5.03%的用户