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.

    在数组中找两个相等的数,如果他们索引之差的绝对值  <= k  则返回true

    C++(26ms):

     1 class Solution {
     2 public:
     3     bool containsNearbyDuplicate(vector<int>& nums, int k) {
     4         unordered_set<int> s ;
     5         int len = nums.size() ;
     6         for (int i = 0 ; i < len ; i++){
     7             if (i > k)
     8                 s.erase(nums[i-k-1]) ;
     9             if (!s.insert(nums[i]).second)
    10                 return true ;
    11         }
    12         return false ;
    13     }
    14 };

    C++(155ms):

     1 class Solution {
     2 public:
     3     bool containsNearbyDuplicate(vector<int>& nums, int k) {
     4         unordered_map<int,int> Map ;
     5         int len = nums.size() ;
     6         bool flag = false ;
     7         for (int i = 0; i < len;i++ ){
     8             if (Map[nums[i]]){
     9                 int t = abs(i+1 - Map[nums[i]]) ;          
    10                 Map[nums[i]] = i+1 ;
    11                 if (t <= k){
    12                     flag = true ;
    13                     break ;
    14                 }   
    15             }else{
    16                 Map[nums[i]] = i+1 ;
    17                 cout<<Map[nums[i]]<<endl ;
    18             }
    19         }
    20         if (flag)
    21             return true ;
    22         else
    23             return false ;
    24         }
    25 };
  • 相关阅读:
    Tools
    Python
    Python
    Python
    Python
    Python
    linux下搭建SVN服务器完全手册【摘抄】
    XPath学习:轴(14)——总结
    XPath学习:parent,child
    使用Xpath对XML进行模糊查询
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/7590947.html
Copyright © 2011-2022 走看看