zoukankan      html  css  js  c++  java
  • Contains Duplicate II

    Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between iand j is at most k.

    不能动态维护k+1大小的map,因为若有相同元素,删除元素时会将新加入的相同大小的元素删掉,导致错误。

     1 class Solution {
     2 public:
     3     bool containsNearbyDuplicate(vector<int>& nums, int k) {
     4         map<int,int> hmap;
     5         int n=nums.size();
     6         if(n<2) return false;
     7         for(int i=0;i<n;i++)
     8         {
     9             if(hmap.count(nums[i])&&i-hmap[nums[i]]<=k)
    10                 return true;
    11             else
    12                 hmap[nums[i]]=i;
    13             
    14         }
    15         return false;
    16     }
    17 };
  • 相关阅读:
    idea编辑器快捷键
    双随机系统遇到的简单样式问题
    HTTP笔记八
    HTTP笔记七
    HTTP笔记六
    HTTP笔记五
    HTTP笔记四
    HTTP笔记三
    HTTP笔记二
    HTTP笔记一
  • 原文地址:https://www.cnblogs.com/zl1991/p/4686223.html
Copyright © 2011-2022 走看看