zoukankan      html  css  js  c++  java
  • [LeetCode] Contains Duplicate II

    Well, the basic idea is fairly straightforward. We maintain a mapping mp from a value in nums to its position (index) i. Each time we meet an unseen value, we add it to the map (mp[nums[i]] = i). Otherwise, depending on whether the recorded index mp[nums[i]] and the current index isatisfy i - mp[nums[i]] <= k (node that the new index i is larger than the old indexmp[nums[i]]), we return true or update the index (mp[nums[i]] = i). If all the elements have been visited and we have not returned true, we will return false.

    1     bool containsNearbyDuplicate(vector<int>& nums, int k) {
    2         unordered_map<int, int> mp; 
    3         for (int i = 0; i < nums.size(); i++) {
    4             if (mp.find(nums[i]) != mp.end() && i - mp[nums[i]] <= k)
    5                 return true;
    6             mp[nums[i]] = i; 
    7         }
    8         return false; 
    9     }
  • 相关阅读:
    C语言基础
    R安装包
    随笔
    计算机组成原理(三)--存储器的层次结构
    计算机组成原理(一)
    查找
    二叉树
    Mesos
    第三章 线性表
    第四章 栈与队列
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4548006.html
Copyright © 2011-2022 走看看