码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][Java]Contains Duplicate III

时间:2015-12-28 23:19:22      阅读:456      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

 


 

 

数组中是否存在两个元素,他们的值小于等于t,并且下标小于等于k。

Javascript时间很宽松,暴力O(n^2)直接可以过,但这题应该是希望我们用二叉搜索树。

可以把k看做滑动窗口,对于一个新的数,可以想象成放到这个窗口的最左边或者最右边,如果这个数+t或-t之后落在窗口里,直接返回true。

https://leetcode.com/discuss/38177/java-o-n-lg-k-solution

 

Java BST: 

 1 public class Solution {
 2     public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
 3         TreeSet<Integer> treeSet = new TreeSet<Integer>();
 4         for(int i = 0; i < nums.length; i++){
 5             Integer floor = treeSet.floor(nums[i] + t);
 6             Integer ceiling = treeSet.ceiling(nums[i] - t);
 7             if( (floor != null && floor >= nums[i]) 
 8                 || (ceiling != null && ceiling <= nums[i]) ) return true;
 9             treeSet.add(nums[i]);
10             if(treeSet.size() > k) treeSet.remove(nums[i - k]);
11         }
12         return false;
13     }
14 }

 

Brute Force:

 1 /**
 2  * @param {number[]} nums
 3  * @param {number} k
 4  * @param {number} t
 5  * @return {boolean}
 6  */
 7 var containsNearbyAlmostDuplicate = function(nums, k, t) {
 8     for(var i = 0; i < nums.length; i++)
 9         for(var j = i + 1; j < nums.length; j++)
10             if(Math.abs(nums[i] - nums[j]) <= t && Math.abs(i - j) <= k)
11                 return true;
12     return false;
13 };

 

[LeetCode][Java]Contains Duplicate III

标签:

原文地址:http://www.cnblogs.com/Liok3187/p/5084305.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!