Contains Duplicate III

来源:互联网 发布:手机淘宝怎么寄件 编辑:程序博客网 时间:2024/05/20 03:06

题目链接

思路:
这个题纠结了我一天。开始是思路不会,后来是各种程序溢出。
我在定义数组的时候用的是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;    }}
0 0
原创粉丝点击