开始刷leetcode day63:Contains Duplicate III
2015-07-13 06:04
507 查看
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.
Java:
public class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
TreeSet<Integer> treeset = new TreeSet<Integer>();
for(int i=0; i< nums.length; i++)
{
if(!treeset.isEmpty())
{
if(treeset.floor(nums[i]) != null && nums[i] <= treeset.floor(nums[i])+t)
return true;
else if(treeset.ceiling(nums[i]) != null && treeset.ceiling(nums[i]) - nums[i]<=t)
return true;
//find the highest value inside the set that is less than nums[i] or the smallest value bigger than nums[i]
}
treeset.add(nums[i]);
if(i>=k)
{
treeset.remove(nums[i-k]);
}
}
return false;
}
}
注意,使用了窗口用于维持size k。
使用了treeset的两个函数,floor 和ceiling
nums[i] <= treeset.floor(nums[i])+t 而不是 nums[i] - treeset.floor(nums[i]) <= t 特例为 [-1,Integer.Max]
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.
Java:
public class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
TreeSet<Integer> treeset = new TreeSet<Integer>();
for(int i=0; i< nums.length; i++)
{
if(!treeset.isEmpty())
{
if(treeset.floor(nums[i]) != null && nums[i] <= treeset.floor(nums[i])+t)
return true;
else if(treeset.ceiling(nums[i]) != null && treeset.ceiling(nums[i]) - nums[i]<=t)
return true;
//find the highest value inside the set that is less than nums[i] or the smallest value bigger than nums[i]
}
treeset.add(nums[i]);
if(i>=k)
{
treeset.remove(nums[i-k]);
}
}
return false;
}
}
注意,使用了窗口用于维持size k。
使用了treeset的两个函数,floor 和ceiling
nums[i] <= treeset.floor(nums[i])+t 而不是 nums[i] - treeset.floor(nums[i]) <= t 特例为 [-1,Integer.Max]
相关文章推荐
- 开始刷leetcode day63:Contains Duplicate II
- 开始刷leetcode day63: Contains Duplicate
- mail -s发送附件
- mail -s发送附件
- static--main--单例
- 2015Summer Training #2
- 配置SSH时遇到 "Host key verification failed." 的解决方案
- lightoj 1021 Painful Bases (状压dp)
- 使用Genymotion调试出现错误INSTALL_FAILED_CPU_ABI_INCOMPATIBLE解决办法
- 启动hive报错[ERROR] Terminal initialization failed; falling back to unsupported
- Air Raid(最小路径覆盖)
- Debug Assertion Failed问题解决
- 带参数main函数
- win7下cmake编译opencv2.3.1生成opencv—createsamples.exe和opencv_haartrainingd.exe
- openCV中waitKey函数介绍
- poj 1273 Drainage Ditches(最大流入门)
- Climbing Stairs
- hdu 1789 Doing Homework again(贪心)
- HDU 1532 Drainage Ditches 排水渠(最大流,入门)
- See you again(电影《速度与激情7》主题曲)