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

LeetCode——Contains Duplicate III

时间:2015-11-03 22:31:59      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

Description:

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和k。判断是否满足下列条件的数。存在两个不同的下标i,j满足: nums[i] - nums[j] | <= t 且 | i - j | <= k。

思路:使用Java中的TreeSet,TreeSet是有序的内部是红黑树实现的。并且内部带有操作方法很方便,会降低问题的复杂度。其实就是一个滑动窗口,把可能满足条件的范围从左向右滑动,直到找出满足条件的数或者窗口滑动完毕。

实现代码:

 

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

 

技术分享

 

LeetCode——Contains Duplicate III

标签:

原文地址:http://www.cnblogs.com/wxisme/p/4934371.html

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