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;
    }
    
  • 相关阅读:
    AcWing
    AcWing
    AcWing
    AcWing
    AcWing
    2019牛客国庆集训派对day1
    模板
    2019南昌网络赛H The Nth Item 矩阵快速幂
    ACwing92 递归实现指数型枚举 dfs
    ACwing91 最短Hamilton路径 状压dp
  • 原文地址:https://www.cnblogs.com/ZhongliangXiang/p/7357045.html
Copyright © 2011-2022 走看看