leetcode219 Contains Duplicate II-zh
# 219. 存在重复元素 II (opens new window)
English Version (opens new window)
# 题目描述
给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的 绝对值 至多为 k。
示例 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
# 解法
# Python3
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
helper = {}
for i, v in enumerate(nums):
if v in helper and i - helper[v] <= k:
return True
helper[v] = i
return False
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# Java
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer, Integer> helper = new HashMap<>();
for (int i = 0, n = nums.length; i < n; ++i) {
if (helper.containsKey(nums[i])) {
int j = helper.get(nums[i]);
if (i - j <= k) {
return true;
}
}
helper.put(nums[i], i);
}
return false;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# ...
1
编辑 (opens new window)
上次更新: 2021/10/30, 12:58:38