---
title: "Contains Duplicate III"
author: "KickCode"
date: "2016-02-21T03:17:40Z"
tags: []
categories: ["编程语言"]
slug: "contains-duplicate-iii"
draft: false
lastmod: "2016-02-21T03:17:40Z"
id: 2277656
url: "https://kickcode.iteye.com/blog/2277656"
---

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* and nums is at most t and the difference between i and j is at most k.

题目中给定一个数组，判断数组中是否存在两个数nums*和nums，它们之间的差最大为t, 两个下标i和j之间的差最大为k。我们用TreeSet来解决，我们维护一个大小为k的treeset，然后通过subSet方法来判断在区间中是否存在和当前元素差小于等于t的元素。为了防止越界，我们将TreeSet设定成长整型。代码如下：

```java

public class Solution {
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        if(nums == null || nums.length == 0 || t < 0) return false;
        TreeSet<Long> set = new TreeSet<Long>();
        set.add((long)nums[0]);
        for(int i = 1; i < nums.length; i++) {
            if(i > k) set.remove((long)nums[i - k - 1]);
            long left = (long)nums[i] - t;
            long right = (long)nums[i] + t;
            if(!set.subSet(left, right + 1).isEmpty()) return true;
            set.add((long)nums[i]);
        }
        return false;
    }
}

```