LeetCode 219. Contains Duplicate II

本文介绍了一种算法,用于判断数组中是否存在两个相等的元素且它们的下标之差不超过给定值k。提供了两种实现方法:一种使用HashMap记录每个元素的位置;另一种使用HashSet存储窗口内的元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

分析问题:

给定一个数组,给定一个距离k。如果存在两个数相等,其下标的间隔小于等于k,就返回true。否者 返回false。

代码实现:
public boolean containsNearbyDuplicate(int[] nums, int k) {
        if (nums == null || nums.length <= 1) {
            return false;
        }
        Map<Integer, Integer> keyLocationsMap = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++) {
            if (keyLocationsMap.get(nums[i]) != null) {
                if ((i - keyLocationsMap.get(nums[i])) <= k) {
                    return true;
                }
            }
            keyLocationsMap.put(nums[i], i);
        }
        return false;
    }
问题改进:

在上面解法中,使用了一个hashmap来存放一个数的值和下标,当值相等是,然后比较下标。如果下标超过了需要等下下标。可以使用一个hashSet,值存放当前下标之前的k个数,之前的数全部删除。

代码实现:
public boolean containsNearbyDuplicate(int[] nums, int k) {

        Set<Integer> containsSet = new HashSet<Integer>(k );

        for (int i = 0; i < nums.length; i++) {
            if (i > k) {//k+1的时候删除0.
                containsSet.remove(nums[i - k - 1]);
            }
            if (!containsSet.add(nums[i])) {
                return true;
            }
        }
        return false;
    }
总结

将一个问题限定在一定的范围内,设定边界是一种很好的方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值