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

Contains Duplicate III —— LeetCode

时间:2015-06-25 16:51:29      阅读:142      评论: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,下标i和j相差<=k。

解题思路:题目没说数组有序,那就得按照无序处理,可以排序,然后从头遍历;或者用个BST之类的有序数据结构,遍历数组的时候重建一下,重建的过程中判断是否有合法的解,有就返回true,否则重建完之后返回false。

public class Solution {
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        if(nums==null||nums.length==0||k<=0){
            return false;
        }
        TreeSet<Integer> tree = new TreeSet<>();
        for(int i=0;i<nums.length;i++){
            Integer big = tree.floor(nums[i]+t);//floor返回集合里<=指定元素的最大值
            Integer small = tree.ceiling(nums[i]-t);//celing返回集合里>=指定元素的最小值
            if((big!=null&&big>=nums[i])||(small!=null&&small<=nums[i])){
                return true;
            }
            if(i>=k){
                tree.remove(nums[i-k]);
            }
            tree.add(nums[i]);
        }
        return false;
    }
}

 

Contains Duplicate III —— LeetCode

标签:

原文地址:http://www.cnblogs.com/aboutblank/p/4600058.html

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