Contains Duplicate II

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.

思想:創建一個集合,在這個集合中維護k個元素,這k個元素是相對於當前遍歷的元素的前k個元素,當遍歷一個新的元素時,檢查前k個元素中是否有相同的元素出現。

#include<iostream>
#include<unordered_set>
#include<vector>


using namespace std;

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_set<int> preKValueSet;
        if(k <= 0)
            return false;

        if(k >= nums.size())
            k = nums.size() - 1;

        for(int i = 0; i < nums.size(); i++)
        {
            if(i > k)
                preKValueSet.erase(nums[i - k - 1]);
            if(preKValueSet.find(nums[i]) != preKValueSet.end())
                return true;
            preKValueSet.insert(nums[i]);
        }

        return false;
    }
};

還有一種使用哈希表的方式如下

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_map<int, int> m;
        for (int i = 0; i < nums.size(); ++i) {
            if (m.find(nums[i]) != m.end() && i - m[nums[i]] <= k) return true;
            else m[nums[i]] = i;
        }
        return false;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章