220. Contains Duplicate III

题目:包含重复值3

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] andnums[j] is at most t and the difference between i and j is at most k.


题意:

给定一个整数数组,判断其中是否存在两个不同的下标i和j满足:| nums[i] - nums[j] | <= t 并且 | i - j | <= k。


思路一:

使用map数据结构来解,用来记录数字和其下标之间的映射。 这里需要两个指针i和j,刚开始i和j都指向0,然后i开始向右走遍历数组,如果i和j之差大于k,且m中有nums[j],则删除并j加一。这样保证了m中所有的数的下标之差都不大于k,然后我们用map数据结构的lower_bound()函数来找一个特定范围,就是大于或等于nums[i] - t的地方,所有小于这个阈值的数和nums[i]的差的绝对值会大于t (可自行带数检验)。然后检测后面的所有的数字,如果数的差的绝对值小于等于t,则返回true。最后遍历完整个数组返回false。

代码:60ms

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        map<int, int> m;
        int j = 0;
        for (int i=0; i<nums.size(); ++i) {
            //维持一个大小为k的窗口,大于该窗口时,擦除掉第一个值
            if (i-j > k && m[nums[j]]==j) m.erase(nums[j++]);
            //通过m.lower_bound(nums[i] - t)找到在map中刚好比nums[i] - t大一点儿的值的下标
            auto a = m.lower_bound(nums[i] - t); 
            //满足条件,返回true
            if (a!=m.end() && abs(a->first - nums[i]) <= t) return true;
            m[nums[i]] = i;
        }
        return false;
    }
};


思路二:

使用桶排序。

代码:25ms

public class Solution {
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        if (k<1 || t<0) return false;
        Map<Long, Long> map = new HashMap<>();
        for (int i=0; i<nums.length; i++) {
            long remappedNum = (long)nums[i] - Integer.MIN_VALUE;
            long bucket = remappedNum/((long)t + 1);
            if (map.containsKey(bucket) 
                || (map.containsKey(bucket-1) && remappedNum-map.get(bucket-1)<=t)
                || (map.containsKey(bucket+1) && map.get(bucket+1)-remappedNum<=t))
                return true;
            if (map.entrySet().size() >= k) {
                long lastBucket = ((long) nums[i-k]-Integer.MIN_VALUE)/((long)t+1);
                map.remove(lastBucket);
            }
            map.put(bucket, remappedNum);
        }
        return false;
    }
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值