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

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

解法

暴力法

nums.size()和k都大的時候,時間複雜度爲O(n2),運行超時。

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        if(nums.empty()) return false;
        for(int i=0;i<nums.size();i++){
            for(int j=i+1;j<nums.size()&&j<=i+k;j++){
                if(nums[i]==nums[j]) return true;
            }
        }
        return false;
    }
};

映射表

將前面k個數都存在hashtable中,每次查詢當前元素是否在hashtable中。由於unordered_set底層基於hash表實現,其插入、查找、刪除時間複雜度爲O(1),故算法整體時間複雜度O(n)

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