219:存在重复元素 II

This commit is contained in:
轩辕龙儿 2022-01-19 11:08:55 +08:00
parent 1bf9d0ab45
commit 3a770d5c98

View File

@ -21,6 +21,9 @@
package leetcode.editor.cn; package leetcode.editor.cn;
import java.util.HashMap;
import java.util.Map;
//219:存在重复元素 II //219:存在重复元素 II
class ContainsDuplicateIi { class ContainsDuplicateIi {
public static void main(String[] args) { public static void main(String[] args) {
@ -35,12 +38,12 @@ class ContainsDuplicateIi {
if (k <= 0) { if (k <= 0) {
return false; return false;
} }
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) { for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j <= Math.min(i + k, nums.length - 1); j++) { if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) {
if (nums[i] == nums[j]) { return true;
return true;
}
} }
map.put(nums[i], i);
} }
return false; return false;
} }