leetcode 219. Contains Duplicate II (重复数字II)

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.

Example 1:

Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:

Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:

Input: nums = [1,2,3,1,2,3], k = 2
Output: false

给出一个数组,让判断是否存在nums[i] == nums[j] 而且下标i和j的差<=k

思路:

既然要求相等的俩数下标的差不能超过k,
那么当然是下标的差越小越好,
当遍历到相同的数字时,如果同时有好几个相同的数字,那自然是取之前遍历过的最右边的数字的下标,
比如example2中的[1,0, 1, 1],遍历到最后一个1的时候,它前面有2个相同的数字1,要选最右边的1,这样下标差才最小。

既然这样,只需要一个hash map, 保存数字和它对应的最新的下标(最右边的),
遇到相同的数字时,用当前下标减去hash map中保存的下标,只要差<=k,就返回true.
其实不需要计算差的绝对值,因为是从左到右遍历的,右边的下标肯定比左边的大。

public boolean containsNearbyDuplicate(int[] nums, int k) {
    HashMap<Integer, Integer> map = new HashMap<>();
    int i = 0;
    
    for(int num : nums) {
        if(map.containsKey(num)) {
            if(i - map.get(num) <= k) return true;           
        }
        map.put(num, i);
        i++;
    }
    return false;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值