zoukankan      html  css  js  c++  java
  • Leetcode Contains Duplicate III

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


    解题思路:

    关键是要想到用TreeSet或者SortedSet, 而且要维护好k 的窗口!!!

    另外,要考虑溢出情况,所以必须使用long !!!!

    方法一: TreeSet 用的是Binary Search Tree, 有两个有用的method: ceiling() and floor(), the time complexity is O(nlog(k)).

    ceiling() : Returns the least element in this set greater than or equal to the given element, or null if there is no such element.

    floor() : Returns the greatest element in this set less than or equal to the given element, or null if there is no such element.

    方法二: SortedSet 可以界定左边界和右边界。

    两个方法的共同点是维护好k的窗口。


     Java code:

    方法一:

     public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
            if(k < 1 || t < 0) {
                return false;
            }   
            TreeSet<Long> set = new TreeSet<Long>();
            for(int i= 0; i< nums.length; i++) {
                long x = (long)nums[i];
                if((set.floor(x) != null && (x-(long)(set.floor(x)) <=(long)t)) 
                   || (set.ceiling(x)!=null && ((long)(set.ceiling(x))-x <=(long)t))) {
                    return true;
                }
                set.add(x);
                if(i>=k) {
                    set.remove((long)nums[i-k]);
                }
            }
            return false;
        }

    方法二:

    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
            if(k < 1 || t < 0) {
                return false;
            }
            SortedSet<Long> set = new TreeSet<Long>();
            for(int i =0; i< nums.length; i++) {
                long leftBound = (long)nums[i]-t;
                long rightBound = (long)nums[i]+t+1;
                SortedSet<Long> subSet = set.subSet(leftBound, rightBound);
                if(!subSet.isEmpty()){
                    return true;
                }
                set.add((long)nums[i]);
                if(i>=k) {
                    set.remove((long)nums[i-k]);
                }
            }
            return false;
        }

    Reference:

    1. http://www.programcreek.com/2014/06/leetcode-contains-duplicate-iii-java/

  • 相关阅读:
    LR与SVM的异同
    精确率,召回率
    XgBoost推导与总结
    梯度下降中的步长选择-线性搜索
    页面去掉某个css属性
    composer 安装某个插件后 引入方法
    javascript,检测对象中是否存在某个属性
    js 计算字符串长度 中文为2 英文为1
    laravel 新手 =_= 持续更新
    php compact() 函数
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4827824.html
Copyright © 2011-2022 走看看