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,判断该数组中是否存在不同下标的 i 和 j 两个元素,使得 nums[i] = nums[j],且 i 和 j 的差不超过k。

     1     public boolean containsNearbyDuplicate(int[] nums, int k) {
     2         if (nums == null || nums.length == 0)
     3             return false;
     4         Map<Integer, List<Integer>> numberMap = new HashMap<>();
     5         for (int i = 0; i < nums.length; i++) {
     6             List<Integer> indexs = numberMap.getOrDefault(nums[i], new ArrayList<>());
     7             indexs.add(i);
     8             numberMap.put(nums[i], indexs);
     9         }
    10         for (Map.Entry<Integer,List<Integer>> entry:numberMap.entrySet())
    11         {
    12             if (entry.getValue().size()>1)
    13             {
    14                 List<Integer> indexs = entry.getValue();
    15                 for (int i=indexs.size()-1; i>0;i--)
    16                 {
    17                     if(indexs.get(i) - indexs.get(i-1) <= k)
    18                         return true;
    19                 }
    20             }
    21         }
    22         return false;        
    23     }
  • 相关阅读:
    SPOJ distinct subtrings
    OI题目类型总结整理
    emacs 考场配置
    SDOI2013 费用流
    HAOI2011 problem a
    BZOJ3438 小M的作物(和拓展)
    APIO2014 连珠线
    NOI2009 管道取珠
    HNOI2013 切糕
    NOI2009 植物大战僵尸
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7668698.html
Copyright © 2011-2022 走看看