LeetCode-Contains Duplicate II

Description:
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

题意:给定一个一维数组num和一个最大距离k;要求判断数组中是否存在两个不同位置相等的元素,且这两个元素之间的最大距离为k;

解法一:最简单的办法就是遍历所有的可能,我们对每一个元素,判断在最大距离k之内是否存在相等的元素;

Java
class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j <= Math.min(i + k, nums.length - 1); j++) {
                if (nums[i] == nums[j]) {
                    return true;
                }
            }
        }
        return false;
    }
}

解法二:我们可以利用哈希表来实现,以元素值及下标作为键值对;在遍历数组的时候,将哈希表中不存在的元素存入到表中,当遇到表中存在的元素时,比较两者的下标差是否在最大距离k之内,如果没有,则更新此元素的下标为当前元素下标,继续遍历直到找到相等元素亦或者遍历完数组;

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Map<Integer, Integer> table = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (table.containsKey(nums[i]) && i - table.get(nums[i]) <= k) {
                return true;
            } else {
                table.put(nums[i], i);
            }
        }
        return false;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值