Skip to content

Commit 32b7af2

Browse files
committed
update
1 parent a610d8a commit 32b7af2

4 files changed

+38
-0
lines changed

leetcode_solved/[editing]leetcode_0217_Contains_Duplicate.cpp

Whitespace-only changes.

leetcode_solved/[editing]leetcode_0219_Contains_Duplicate_II.cpp

Whitespace-only changes.
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// AC:T:O(n), S:O(n)
2+
class Solution {
3+
public boolean containsDuplicate(int[] nums) {
4+
HashSet<Integer> record = new HashSet<>();
5+
int size = nums.length;
6+
for(int i = 0; i < size; i++) {
7+
if (record.contains(nums[i])) {
8+
return true;
9+
}
10+
record.add(nums[i]);
11+
}
12+
return false;
13+
}
14+
}
15+
16+
// 法二:先排序,再判断连续两个元素是否相等。
17+
// T:O(n logn), S:O(logn) (调用栈深度)
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* AC: Runtime: 5 ms, faster than 91.91% of Java online submissions for Contains Duplicate II.
3+
* Memory Usage: 45 MB, less than 30.98% of Java online submissions for Contains Duplicate II.
4+
* T: O(n), S: O(n)
5+
* hashmap 存某个元素最近一次出现的位置,和当前如果相同的元素比较索引,如果之差绝对值 <= k 即满足返回。
6+
*/
7+
class Solution {
8+
public boolean containsNearbyDuplicate(int[] nums, int k) {
9+
HashMap<Integer, Integer> record = new HashMap<Integer, Integer>();
10+
int size = nums.length;
11+
for(int i = 0; i < size; i++) {
12+
if (record.get(nums[i]) != null) {
13+
if (i - record.get(nums[i]) <= k) {
14+
return true;
15+
}
16+
}
17+
record.put(nums[i], i);
18+
}
19+
return false;
20+
}
21+
}

0 commit comments

Comments
 (0)