zoukankan      html  css  js  c++  java
  • 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).

    首先想到,用map<int, int>, 其中key = A[i], value = i;
    还想到, 同一个key可以挂多个value. 所以就有了下面的代码.
    自己代码:

    bool containsNearbyDuplicate(vector<int>& A, int k) {
        map<int, int> map;
        for (int i = 0; i < A.size(); i++) {
            if (map.find(A[i]) != map.end() && (i - map[A[i]]) <= k)
                return true;
            map[A[i]] = i;
        }
        return false;
    }
    

    人家代码:

    人家代码, 用set
    核心是: 维护一个set,其中只包含i之前的k个元素,有重复的也会被set干掉.
    如k=3, 当前i=4, 下面indx=0的元素应从set中删除!
    0       1 2 3      4
    
    bool containsNearbyDuplicate(vector<int>& A, int k) {
        unordered_set<int> set; //基于hash实现,比set查询速度快
        if (k < 0) return false;
        for (int i = 0; i < A.size(); i++) {
            if (i > k) set.erase(A[i - k - 1]);
            if (set.find(A[i]) != set.end()) return true;
            set.insert(A[i]);
        }
        return false;
    }
    
  • 相关阅读:
    【译】NodeJS and Good Practices
    【译】单一责任原则
    CSS 属性 z-index
    Node 连接 MySql
    CentOS 7 后台克隆远程库
    H5log打印
    利用Promise实现Promise.all
    Set、Map、WeakSet、WeakMap 理解与使用
    vue如何禁止弹窗后面的滚动条滚动?
    vue面试题总结
  • 原文地址:https://www.cnblogs.com/ZhongliangXiang/p/7357045.html
Copyright © 2011-2022 走看看