码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Contains Duplicate III

时间:2015-06-15 14:37:25      阅读:81      评论:0      收藏: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<Long> windowNumSet = new TreeSet<Long>();
        for(int i = 0; i < nums.length; i++){
            SortedSet<Long> 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
    }
}


LeetCode Contains Duplicate III

标签:

原文地址:http://blog.csdn.net/yangliuy/article/details/46502955

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!