-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNo3DuplicateNum.java
More file actions
73 lines (64 loc) · 1.46 KB
/
No3DuplicateNum.java
File metadata and controls
73 lines (64 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.wzx.sword;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* @see <a href="https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/">https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/</a>
* @author wzx
*/
public class No3DuplicateNum {
/**
* 先排序再查找
* <p>
* time: O(nlogn)
* space: O(1)
*/
public int findRepeatNumber1(int[] nums) {
Arrays.sort(nums);
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[i - 1]) {
return nums[i];
}
}
return -1;
}
/**
* 哈希表
* <p>
* time: O(n)
* space: O(n)
*/
public int findRepeatNumber2(int[] nums) {
Set<Integer> numSet = new HashSet<>();
for (int num : nums) {
if (numSet.contains(num)) {
return num;
} else {
numSet.add(num);
}
}
return -1;
}
/**
* 由于数字在0~n-1之间,以符号位替代哈希表记录已经出现的数字
* 对于0替换为n作为特殊处理
* <p>
* time: O(n)
* space: O(1)
*/
public int findRepeatNumber3(int[] nums) {
for (int i = 0; i < nums.length; i++) {
int num = Math.abs(nums[i]);
// 0替换为n
if (num == nums.length) num = 0;
if (nums[num] < 0) return num;
if (nums[num] == 0) {
// 0替换为n
nums[num] = -nums.length;
} else {
nums[num] = -nums[num];
}
}
return -1;
}
}