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.

    Solution 1: use multimap to store the num:index in the order of increasing num. use it2 to point to the previous element of it. The time complexity is O(nlog(n)). Note that the iterator here only can increase like ++,can't decrease like --.

     1 class Solution {
     2 public:
     3     bool containsNearbyDuplicate(vector<int>& nums, int k) {
     4         multimap<int,int> m;
     5         int n=nums.size();
     6         for (int i=0;i<n;i++){
     7             m.insert(pair<int,int>(nums[i],i)); //num:index
     8         }
     9         multimap<int,int>::iterator it2=m.end();
    10         for (multimap<int,int>::iterator it=m.begin();it!=m.end();it++){
    11             if (it2!=m.end()){
    12                 if ((*it).first==(*(it2)).first && ((*it).second-(*(it2)).second)<=k) return true;
    13             } 
    14             it2=it;
    15         }
    16         return false;
    17     }
    18 };
  • 相关阅读:
    不同压测场景的区别
    常用的re模块的正则匹配的表达式
    了解爬虫
    robots.txt 协议
    vue前台配置
    短信验证码的使用
    创建表
    数据库配置
    后台:Django项目创建
    虚拟环境的搭建
  • 原文地址:https://www.cnblogs.com/anghostcici/p/6673896.html
Copyright © 2011-2022 走看看