Contains Duplicate III
2015-06-05 11:11
218 查看
Contains Duplicate III
问题: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.
思路:
二分查找树
我的代码:
View Code
学习之处:
之前没注意到java中还有TreeSet这样一个集合,实现的机理是红黑树,所以查找和删除的时间复杂度O(logk),该API在查找和删除上有巨大的优势啊。在涉及到查找历史数据问题的时候,考虑到此
该题的思路是维持一个大小为k的二分查找树
问题: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.
思路:
二分查找树
我的代码:
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<Integer>(); for(int i=0; i<nums.length; i++) { Integer floor = tree.floor(nums[i]+t); Integer ceil = tree.ceiling(nums[i]-t); if((floor!=null && floor>=nums[i]) || (ceil!=null && ceil<=nums[i])) return true; tree.add(nums[i]); if(i >= k) tree.remove(nums[i-k]); } return false; } }
View Code
学习之处:
之前没注意到java中还有TreeSet这样一个集合,实现的机理是红黑树,所以查找和删除的时间复杂度O(logk),该API在查找和删除上有巨大的优势啊。在涉及到查找历史数据问题的时候,考虑到此
该题的思路是维持一个大小为k的二分查找树
相关文章推荐
- 进程控制 [fork() exec() wait() waitpid()]
- 强人工智能基本问题:全局控制与自组织
- SharePoint 2013上传AI格式文件,再次下载后变成了PS格式文件
- leetcode_70题——Climbing Stairs(简单DP题)
- 11. Container With Most Water
- Naive Bayes在mapreduce上的实现
- leetcode 217: Contains Duplicate
- 正确使用Block避免Cycle Retain和Crash
- LeetCode "Contains Duplicate III"
- sgu252:Railway Communication(费用流)
- Climbing Stairs
- 从main函数中argc和argv开始学习
- [LOJ 1038] Race to 1 Again
- How did your survive waiting
- TurboMail智能防御企业邮箱盗号和退信攻击
- tools:context=".MainActivity的作用
- 用libaio读写文件时遇到的问题
- UVA514 Rails
- UVA442 Matrix Chain Multiplication
- light oj 1038 - Race to 1 Again(概率dp求期望 记忆化搜索)