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 };
  • 相关阅读:
    POJ10024873279
    javascript中转为二进制
    javascript画图库
    javascript返回多个参数
    单引号,双引号,javascript,HTML,转义字符
    onKeypress对中文无效
    javascript参数传址与传值
    关于JS中引用其它JS的问题
    JavaScript中可建立自己的库
    路由表详解
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/7590947.html
Copyright © 2011-2022 走看看