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;
    }
};
发布了103 篇原创文章 · 获赞 9 · 访问量 4708

猜你喜欢

转载自blog.csdn.net/weixin_43590232/article/details/104359062
今日推荐