-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path448.找到所有数组中消失的数字.go
66 lines (63 loc) · 1.31 KB
/
448.找到所有数组中消失的数字.go
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
/*
* @lc app=leetcode.cn id=448 lang=golang
*
* [448] 找到所有数组中消失的数字
*
* https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array/description/
*
* algorithms
* Easy (49.54%)
* Likes: 170
* Dislikes: 0
* Total Accepted: 9K
* Total Submissions: 18K
* Testcase Example: '[4,3,2,7,8,2,3,1]'
*
* 给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
*
* 找到所有在 [1, n] 范围之间没有出现在数组中的数字。
*
* 您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
*
* 示例:
*
*
* 输入:
* [4,3,2,7,8,2,3,1]
*
* 输出:
* [5,6]
*
*
*/
func findDisappearedNumbers(nums []int) []int {
n := len(nums)
if n <= 0 {
return []int{}
}
i := 0
for i < n {
if nums[i] == (i + 1) {
i++
} else {
val := nums[i]
if nums[val-1] == nums[i] {
i++
} else {
nums[val-1], nums[i] = nums[i], nums[val-1]
}
}
}
result := make([]int, 0)
for i := 0; i < n; i++ {
if nums[i] != (i + 1) {
result = append(result, i+1)
}
}
return result
}
// 4,3,2,7,8,2,3,1
// 7,3,2,4,8,2,3,1
// 3,3,2,4,8,2,7,1
// 2,3,3,4,8,2,7,1
// 3,2,3,4,8,2,7,1