IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [原]LeetCode Contains Duplicate III

    yangliuy发表于 2015-06-15 14:02:42
    love 0

    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.

    思路分析:这题有几个要注意的地方:第一是如何快速搜索是否存在于某个数差值在t以内的数,可以使用TreeSet的subSet函数,可以返回在TreeSet中从在[lower,upper)的数,注意是前闭后开,这个函数返回的是SortedSet接口类型,TreeSet基于BST实现,特别适合于某个range里面的数的快速查找,下面的算法复杂度是O(nlogk)。第二,和Contains Duplicate的前面两题一样,有“the difference between i and j is at most k.”这样的限定的题目我们可以考虑维护一个长度为k的滑动窗口。第三,如果用Integer类型,这题有个test case会使得nums[i] + t + 1溢出变成负数,因此需要使用Long类型来保存数,要注意类型转换。

    AC Code

    import java.util.SortedSet;  // the return value of subset is SortedSet(Interface) type
    public class Solution {
        public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
            //1018
            if(nums == null || nums.length < 2 || k < 1 || t < 0) return false; // t is at least 0, k is at least 1
            SortedSet windowNumSet = new TreeSet();
            for(int i = 0; i < nums.length; i++){
                SortedSet set = windowNumSet.subSet((long)nums[i]-t, (long)nums[i] + t + 1);
                if(!set.isEmpty()) return true;
                if(i >= k) windowNumSet.remove((long)nums[i-k]);
                windowNumSet.add((long)nums[i]);
            }
            return false;
            //1026
        }
    }




沪ICP备19023445号-2号
友情链接