LeetCode 0219.存在重复元素 II:哈希表

时间:2025-01-30 06:59:41

【LetMeFly】219.存在重复元素 II:哈希表

力扣题目链接:https://leetcode.cn/problems/contains-duplicate-ii/

给你一个整数数组 nums 和一个整数 k ,判断数组中是否存在两个 不同的索引 i 和 j ,满足 nums[i] == nums[j]abs(i - j) <= k 。如果存在,返回 true ;否则,返回 false

 

示例 1:

输入:nums = [1,2,3,1], k = 3
输出:true

示例 2:

输入:nums = [1,0,1,1], k = 1
输出:true

示例 3:

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

 

 

提示:

  • 1 <= nums.length <= 105
  • -109 <= nums[i] <= 109
  • 0 <= k <= 105

解题方法:哈希表

使用哈希表记录每个元素最后一次出现的位置。

遍历nums数组,如果当前元素在哈希表中出现过并且这次和上次出现位置只差不超过 k k k,则返回true

每次遍历完一个数组,更新哈希表中这个数字的“最后出现位置”。

  • 时间复杂度 O ( l e n ( n u m s ) ) O(len(nums)) O(len(nums))
  • 空间复杂度 O ( l e n ( n u m s ) ) O(len(nums)) O(len(nums))

AC代码

C++
/*
 * @Author: LetMeFly
 * @Date: 2025-01-29 11:48:29
 * @LastEditors: LetMeFly.xyz
 * @LastEditTime: 2025-01-29 11:49:49
 */
class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_map<int, int> ma;
        for (int i = 0; i < nums.size(); i++) {
            if (ma.count(nums[i]) && i - ma[nums[i]] <= k) {
                return true;
            }
            ma[nums[i]] = i;
        }
        return false;
    }
};
Python
'''
Author: LetMeFly
Date: 2025-01-29 11:51:06
LastEditors: LetMeFly.xyz
LastEditTime: 2025-01-29 11:51:09
'''
from typing import List

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        ma = dict()
        for i, t in enumerate(nums):
            if t in ma and i - ma[t] <= k:
                return True
            ma[t] = i
        return False
Java
/*
 * @Author: LetMeFly
 * @Date: 2025-01-29 11:53:14
 * @LastEditors: LetMeFly.xyz
 * @LastEditTime: 2025-01-29 11:55:24
 */
import java.util.HashMap;

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        HashMap<Integer, Integer> ma = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (i - ma.getOrDefault(nums[i], -1000000) <= k) {
                return true;
            }
            ma.put(nums[i], i);
        }
        return false;
    }
}
Go
/*
 * @Author: LetMeFly
 * @Date: 2025-01-29 11:56:06
 * @LastEditors: LetMeFly.xyz
 * @LastEditTime: 2025-01-29 11:57:59
 */
package main

func containsNearbyDuplicate(nums []int, k int) bool {
    ma := map[int]int{}
    for i, t := range nums {
        if p, ok := ma[t]; ok && i - p <= k {
            return true
        }
        ma[t] = i
    }
    return false
}

Happy New Year! 健康第一。

同步发文于****和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~

Tisfy:https://letmefly.blog.****.net/article/details/145392757