• 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     }
  • 相关阅读:
    29. Divide Two Integers
    leetCode 17. Letter Combinations of a Phone Number
    查找
    快速排序
    希尔排序
    插入排序
    归并排序,还有非递归方式没写
    堆排序--还有递归法没有写
    c++实现字符串全排序
    归并排序
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7668698.html
Copyright © 2020-2023  润新知