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 };
  • 相关阅读:
    node下运行ts
    npm的一些基本配置设置
    windws 安装jdk
    java jdbc连接mysql
    struts2+jquery 实现ajax登陆
    struts2 零配置
    java 生成UUID
    ubuntu 换源
    ubuntu下安装redis
    安装 vsftpd
  • 原文地址:https://www.cnblogs.com/anghostcici/p/6673896.html
Copyright © 2011-2022 走看看