219.Contains Duplicate II:修订间差异
创建页面,内容为“=Description= {{LeetCode |id=triangle |no=219 |difficulty=Medium |category=Array |collection=Top 150 |title=Contains Duplicate II |summary=Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.}} Example 1: <syntaxhighlight lang="bash"> Input: nums = [1,2,3,1], k = 3 Output: true </syntaxhighlight> Example 2: <syntaxhighlight lang="bash"> Input: nums =…” |
|||
第52行: | 第52行: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
== | == Sliding Window== | ||
{{Submission|runtime=16ms|memory=56.88MB|rp=93.06|mp=53.61}} | {{Submission|runtime=16ms|memory=56.88MB|rp=93.06|mp=53.61}} | ||
第59行: | 第59行: | ||
public boolean containsNearbyDuplicate(int[] nums, int k) { | public boolean containsNearbyDuplicate(int[] nums, int k) { | ||
if(k == 0 || nums.length < 2) return false; | if(k == 0 || nums.length < 2) return false; | ||
Set<Integer> | Set<Integer> window = new HashSet<>(); | ||
for(int i = 0, j = 0; j < nums.length; j++) { | for(int i = 0, j = 0; j < nums.length; j++) { | ||
if(! | if(!window.add(nums[j])) return true; | ||
if(set.size() >= k + 1) | if(set.size() >= k + 1) | ||
window.remove(nums[i++]); | |||
} | } | ||
return false; | return false; |
2024年2月27日 (二) 14:36的最新版本
Description
#219 | Contains Duplicate II | Medium | ||
---|---|---|---|---|
Array | Top 150 | |||
Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= 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
Solution
Two-pointers
Runtime 2012ms |
|
Memory 58.45MB |
|
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if(k == 0) return false;
int left = 0, right = 1;
while(left < nums.length && right < nums.length) {
//System.out.println(left + " " + right);
if(nums[left] == nums[right])
return true;
if(right - left < k && right < nums.length -1)
right ++;
else {
left ++;
right = left + 1;
}
}
return false;
}
}
Sliding Window
Runtime 16ms |
|
Memory 56.88MB |
|
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if(k == 0 || nums.length < 2) return false;
Set<Integer> window = new HashSet<>();
for(int i = 0, j = 0; j < nums.length; j++) {
if(!window.add(nums[j])) return true;
if(set.size() >= k + 1)
window.remove(nums[i++]);
}
return false;
}
}