leet-code/src/main/java/leetcode/editor/cn/ContainsDuplicateIi.java
2022-01-19 11:08:55 +08:00

53 lines
1.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//给定一个整数数组和一个整数 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
// Related Topics 数组 哈希表 滑动窗口 👍 306 👎 0
package leetcode.editor.cn;
import java.util.HashMap;
import java.util.Map;
//219:存在重复元素 II
class ContainsDuplicateIi {
public static void main(String[] args) {
//测试代码
Solution solution = new ContainsDuplicateIi().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if (k <= 0) {
return false;
}
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) {
return true;
}
map.put(nums[i], i);
}
return false;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}