美文网首页
【数组】220.存在重复元素III

【数组】220.存在重复元素III

作者: ___Qian___ | 来源:发表于2019-01-14 10:52 被阅读0次

题目

给定一个整数数组,判断数组中是否有两个不同的索引 i 和 j,使得 nums [i] 和 nums [j] 的差的绝对值最大为 t,并且 i 和 j 之间的差的绝对值最大为 ķ。

示例 1:

输入: nums = [1,2,3,1], k = 3, t = 0
输出: true
示例 2:

输入: nums = [1,0,1,1], k = 1, t = 2
输出: true
示例 3:

输入: nums = [1,5,9,1,5,9], k = 2, t = 3
输出: false

思路

此题目在219号问题基础上多了一个条件:
nums [i] 和 nums [j] 的差的绝对值最大为 t


把查找表修改为有序的TreeMap,使用ceiling(e)函数,在查找表中找比v-t大的最小元素,若存在且该元素小于等于v+t,说明该元素正好在[v-t,v+t]之间,符合条件
同时此题还要注意整形溢出问题。

class Solution {
   public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        TreeSet<Long> record = new TreeSet<>();
        for(int i = 0; i<nums.length; i++){
            //重点修改此处,注意防止整形溢出
            //ceiling(e)函数用来取大于等于e的最小元素
            if(record.ceiling((long)nums[i] - (long)t) != null &&
                    record.ceiling((long)nums[i] - (long)t) <= (long)nums[i] + (long)t)
                return true;
            else
                record.add((long)nums[i]);
            if(record.size()==k+1)
                record.remove((long)nums[i-k]);
        }
        return false;
        
    }

}

相关文章

网友评论

      本文标题:【数组】220.存在重复元素III

      本文链接:https://www.haomeiwen.com/subject/tphddqtx.html