思路:
这个题纠结了我一天。开始是思路不会,后来是各种程序溢出。
我在定义数组的时候用的是Integer类型。可是测试用例里面有个是
Integer.Max+t这样就会变成负数。导致计算错误。在编程的时候,程序溢出错误真的是很难处理的一个问题。必须要保证每个运算都不能溢出。
public class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
int n=nums.length;
TreeSet<Long> mySet=new TreeSet<Long>();
for(int i=0;i<n;i++)
{
Long lower=mySet.ceiling((long)(nums[i]-t));
Long uper=mySet.lower((long)(nums[i]+t));
if((lower!=null&&Math.abs(lower-nums[i])<=t)||(uper!=null&&Math.abs(uper-nums[i])<=t))
{
return true;
}
mySet.add((long)nums[i]);
if(i-k>=0)
{
mySet.remove((long)nums[i-k]);
}
}
return false;
}
}
本文通过一个具体的编程问题,探讨了如何避免程序中出现溢出错误,并提供了一段Java代码作为解决方案实例。作者分享了使用TreeSet进行元素查找的经验,确保在给定条件下能正确判断数组中是否存在两个元素其差值不超过指定阈值。

679

被折叠的 条评论
为什么被折叠?



