您的位置:首页 > 大数据 > 人工智能

Middle-题目122:220. Contains Duplicate III

2016-05-31 20:13 453 查看
题目原文:

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.

题目大意:

给出一个数组nums,判断是否存在这样两个下标i和j使得|nums[i]-nums[j]≤t,且|j-i|≤k.

题目分析:

巧用TreeSet这个类,它是一个集合,元素不可重复,不可维护加入集合的顺序,但集合是有序的,有floor(n)和ceiling(n)两个方法取得元素n相邻的两个元素。

那么构造一个TreeSet,并维持TreeSet的长度为K(如果i超过k就把nums[i-k]弹出去)。然后设n=nums[i].每次判断n-floor(n)是否≤t或者ceiling(n)是否≤t(因为TreeSet的长度不超过k,所以如果存在floor(n)或者ceiling(n),其在数组的下标与n的差值必然不超过k),若存在则找到解,返回true,若不存在则加入n,弹出nums[i-k],总的时间复杂度是O(nlogk) (因为TreeSet的add和remove都是logk复杂度的)

源码:(language:java)

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


成绩:

68ms,beats 10.72%,众数23ms,5.88%

Cmershen的碎碎念:

本题类似于滑动窗口,是第一道需要用到TreeSet的题,但是效率不高,可能有O(n)的线性算法。TreeSet基于红黑树实现,它遗失插入顺序但保证集合内有序,而红黑树是一种应用广泛的用于查找的二叉树,关于红黑树的详细了解可自行百度。类似的数据结构还有TreeMap(保证key有序)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: