File tree Expand file tree Collapse file tree 1 file changed +67
-0
lines changed
problems/448. Find All Numbers Disappeared in an Array Expand file tree Collapse file tree 1 file changed +67
-0
lines changed Original file line number Diff line number Diff line change
1
+ # #1 Set[ AC]
2
+
3
+ ## 思路
4
+
5
+ 我们通过` HashSet ` 这种数据结构来记录$1-n$在` nums ` 已经出现过的元素,然后将没出现过的元素返回。
6
+
7
+ ## 算法
8
+
9
+ ``` java
10
+ class Solution {
11
+ public List<Integer > findDisappearedNumbers (int [] nums ) {
12
+ List<Integer > res = new ArrayList<> ();
13
+ if (nums == null || nums. length == 0 ) return res;
14
+ Set<Integer > appear = new HashSet<> ();
15
+ for (int num : nums)
16
+ appear. add(num);
17
+ for (int i= 1 ; i<= nums. length; i++ )
18
+ if (! appear. contains(i))
19
+ res. add(i);
20
+ return res;
21
+ }
22
+ }
23
+ ```
24
+
25
+ ## 性能分析
26
+
27
+ ### 时间复杂度
28
+ $O(n)$
29
+
30
+ ### 空间复杂度
31
+ $O(n)$
32
+
33
+ # #2 标记法[ AC]
34
+
35
+ ## 思路
36
+
37
+ 由于数组中的元素值满足:$1\leq nums[ i] \leq n$,因此$0\leq nums[ i] -1\leq n-1$,这意味着我们可以把$nums[ i] -1$当做数组的下标索引。因此,我们只需要判断该索引是否出现过即可,如何判断呢?我们把$nums[ nums[ i] -1] $当做判别标记。
38
+
39
+ ![ ] ( http://p6sh0jwf6.bkt.clouddn.com/2018-10-19-%E6%A0%87%E8%AE%B0%E6%B3%95.gif )
40
+
41
+ ## 算法
42
+
43
+ ``` java
44
+ class Solution {
45
+ public List<Integer > findDisappearedNumbers (int [] nums ) {
46
+ List<Integer > res = new ArrayList<> ();
47
+ if (nums == null || nums. length == 0 ) return res;
48
+ for (int i= 0 ; i< nums. length; i++ ){
49
+ int idx = Math . abs(nums[i])- 1 ;
50
+ if (nums[idx] > 0 )
51
+ nums[idx] = - nums[idx];
52
+ }
53
+ for (int i= 1 ; i<= nums. length; i++ )
54
+ if (nums[i- 1 ] > 0 )
55
+ res. add(i);
56
+ return res;
57
+ }
58
+ }
59
+ ```
60
+
61
+ ## 性能分析
62
+
63
+ ### 时间复杂度
64
+ $O(n)$
65
+
66
+ ### 空间复杂度
67
+ $O(n)$
You can’t perform that action at this time.
0 commit comments