zoukankan      html  css  js  c++  java
  • [LeetCode] 220. Contains Duplicate III Java

    题目:

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

    题意及分析:

    给出一个数组,要求判断是否存在,对于其中两个不同的元素有:(1) |i-j| <= k (2) |nums[i]-nums[j]| <= t。

    TreeSet(binary search tree)  o(Nlogk)

    利用treeset,用floor方法查找treeSet中大于等于当前值且与当前元素距离小于t的最大元素,然后如果该元素不为空,那么就可以找到符合题意的两个元素。

    或者用用ceiling方法查找treeSet中大于等于当前值且与当前元素距离小于t的最小元素,然后如果该元素不为空,那么就可以找到符合题意的两个元素。

    最后需要注意的一点,就是两个元素之间的距离要小于等于k,即|i-j|<=k,所以当前treeSet中最多只能有k个元素。

    代码:

    class Solution {
        public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
           if(nums==null||nums.length==0||k<=0) return false;
    
           TreeSet<Long> treeSet = new TreeSet<Long>();
           for(int i=0;i<nums.length;i++){
    
               final Long floor = treeSet.floor((long)nums[i]+t);
               final Long ceil = treeSet.ceiling((long)nums[i]-t);
    
               if((floor!=null&&floor>=(long)nums[i])||
                       (ceil!=null&&ceil<=(long)nums[i])){
                   return true;
               }
    
               treeSet.add((long)nums[i]);
               if(i>=k){        //因为元素的坐标差不能超过k,所以在treeSet中最多只能有k个元素
                   treeSet.remove((long)nums[i-k]);
               }
           }
            return false;
        }
    }
    

       

  • 相关阅读:
    策略模式Strategy
    flex项目
    模板方法Template Method
    timer与ScheduledExecutorService
    java两个字符串的相似度
    一个简单的webshell
    状态模式State
    Java性能优化
    责任链模式China of Responsibility
    ns2.34下mflood协议的完美移植
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7521536.html
Copyright © 2011-2022 走看看