算法系列——Contains Duplicate III

来源:互联网 发布:参加java培训班有用吗 编辑:程序博客网 时间:2024/06/05 18:12

题目描述

Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.

实现思路

给定一个整数数组,判断其中是否存在两个不同的下标i和j满足:| nums[i] - nums[j] | <= t 并且 | i - j | <= k。
利用TreeSet ceiling操作或者floor操作,当

set.ceiling(nums[i]-t)<=nums[i]+t 则必然set中必然存在一个nums[j] 使得 nums[i] - nums[j] | <= t。
同时我们利用维护一个大小为 k的滑动窗口,遍历数组即可。

程序实现

public class Solution {    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++){            if(set.ceiling((long)nums[i]-(long)t)!=null && set.ceiling((long)nums[i]-(long)t)<=(long)nums[i]+(long)t)                return true;            set.add((long)nums[i]);            //保持set中最多有k个元素            if(i>=k)                set.remove((long)nums[i-k]);        }        return false;    }}
原创粉丝点击