zoukankan      html  css  js  c++  java
  • 【LeetCode】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 difference between i and jis at most k.

    提示:

    此题考察的是对Hash Table的应用。这里给出两种方法,第一种基于unordered_map(HashMap),第二种基于unordered_set(HashSet)。

    代码:

    unordered_map:

    class Solution {
    public:
        bool containsNearbyDuplicate(vector<int>& nums, int k) {
            unordered_map<int, int> unmap;
            for (int i = 0; i < nums.size(); ++i) {
                if (unmap.find(nums[i]) == unmap.end()) {
                    unmap[nums[i]] = i;
                } else {
                    int dis = i - unmap[nums[i]];
                    if (dis <= k) return true;
                    unmap[nums[i]] = i;
                }
            }
            return false;
        }
    };

    核心思想就是将数作为键,将数的位置作为值。若遇到相同的数,比较位置差异。

    下面是基于unordered_set的方法:

    class Solution {
    public:
        bool containsNearbyDuplicate(vector<int>& nums, int k) {
            unordered_set<int> us;
            for (int i = 0; i < nums.size(); i++) {
                if (i > k) us.erase(nums[i-k-1]);
                if (!us.insert(nums[i]).second) return true;
            }
            return false;
        }
    };

    相当于是维护一个大小为k+1的划窗,如果超出了划窗的大小就剔除划窗中的第一个数字。如果在插入新数字时发现已经存在,说明找到了满足要求的数字。

  • 相关阅读:
    【】Libevent源码解析
    sftp使用
    世界boss设计
    记一次薪酬谈判的教训 .
    一些常用的文件操作代码
    一位总经理的辞职信,以及回复
    JMeter安装、文档参考
    Charles——charles代理菜单proxy总结——external proxy 外部代理设置
    JDK安装
    Charles——charles常用功能——重定向
  • 原文地址:https://www.cnblogs.com/jdneo/p/4745464.html
Copyright © 2011-2022 走看看