219. Contains Duplicate II 两种map的效率

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,记录重复值,并比较器index,第一个本能算法,把所有相同的数字的index都保存了,对是对,效率低。

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        map<int, vector<int>> helper;

        for(int i = 0; i < nums.size(); i++)
        {
            if(helper.count(nums[i]) > 0)
            {
                for(auto item : helper[nums[i]])
                {
                    if(abs(item - i) <= k)
                        return true;
                }
                helper[nums[i]].push_back(i);
            }
            else
                helper[nums[i]].push_back(i);
        }
        return false;
    }
};
后来看别人的答案,才发现,在遍历的过程中,只要保存最近的一个相同数字的index即可,因为远的那个距离更大,所以,有如下算法。

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_map<int, int> helper;

        for(int i = 0; i < nums.size(); i++)
        {
            if(helper.count(nums[i]) > 0)
            {
                if(abs(helper[nums[i]] - i) <= k)
                    return true;
                helper[nums[i]] = i;
            }
            else
                helper[nums[i]] = i;
        }
        return false;
    }
};
Runtime: 48 ms, faster than 79.60% of C++ online submissions for Contains Duplicate II.
Memory Usage: 16.6 MB, less than 30.40% of C++ online submissions for Contains Duplicate II.

上面用了unordered_map,本来对这两种map并没有可以区分,不过针对这个题目倒是有点好奇,所以换了一下,结果还是有明显差异的,无论查找速度还是内存。

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        map<int, int> helper;

        for(int i = 0; i < nums.size(); i++)
        {
            if(helper.count(nums[i]) > 0)
            {
                if(abs(helper[nums[i]] - i) <= k)
                    return true;
                helper[nums[i]] = i;
            }
            else
                helper[nums[i]] = i;
        }
        return false;
    }
};

Runtime: 84 ms, faster than 26.90% of C++ online submissions for Contains Duplicate II.
Memory Usage: 17.1 MB, less than 20.81% of C++ online submissions for Contains Duplicate II.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值