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)
成绩:
68ms,beats 10.72%,众数23ms,5.88%
Cmershen的碎碎念:
本题类似于滑动窗口,是第一道需要用到TreeSet的题,但是效率不高,可能有O(n)的线性算法。TreeSet基于红黑树实现,它遗失插入顺序但保证集合内有序,而红黑树是一种应用广泛的用于查找的二叉树,关于红黑树的详细了解可自行百度。类似的数据结构还有TreeMap(保证key有序)。
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有序)。
相关文章推荐
- 1079. Total Sales of Supply Chain (25)
- leetcode 217. Contains Duplicate
- 1282 - Leading and Trailing ---LightOj1282(快速幂 + 数学)
- 【BZOJ1664】[Usaco2006 Open]County Fair Events 参加节日庆祝【线段覆盖】【贪心】
- Palindrome Pairs
- poj 3378 Crazy Thairs
- 【cf】Restoring Paintie
- [Ruby On Rails] Action Controller - 控制HTTP 流程
- poj 3378 Crazy Thairs
- TortoiseGit安装图解以及(no supported authentication methods avaiable)问题解决
- ORA-02291: integrity constraint: parent key not found
- 第15课:Spark Streaming源码解读之No Receivers彻底思考
- Paint的效果研究
- Codeforces Round #353 (Div. 2) E. Trains and Statistic
- Middle-题目31:11. Container With Most Water
- 机器学习&人工智能书籍
- 解决日志包Failed to load class"org.slf4j.impl.StaticLoggerBinder"
- [HDOJ2473]Junk-Mail Filter(并查集,删除操作,马甲)
- AI:AI是什么?
- AI不与人为敌