• 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/

  • 相关阅读:
    在Java当中如何优雅地处理临时文件
    lombok插件不建议使用的原因
    linux系统下修改tomcat的端口号时,需要修改的地方
    linux系统下报错为:直接在tomcat的bin目录下生成一个错误文件。
    Linux下修改tomcat端口号
    python实现断点续传下载文件
    Python中下划线---完全解读
    linux  指令 备注
    Linux下高并发socket最大连接数所受的各种限制
    python和pywin32实现窗口查找、遍历和点击
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4827824.html
Copyright © 2020-2023  润新知