-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path448.go
42 lines (38 loc) · 1.21 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
package main
import "fmt"
func main() {
fmt.Println(findDisappearedNumbers([]int{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]
//
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
//秒阿
//1. 将数组元素对应为索引的位置加n
//2. 遍历加n后的数组,若数组元素值小于等于n,则说明数组下标值不存在,即消失的数字
func findDisappearedNumbers(nums []int) []int {
for _, num := range nums {
nums[(num-1)%len(nums)] += len(nums)
}
fmt.Println(nums)
res := make([]int, 0)
for index, num := range nums {
if num <= len(nums) {
res = append(res, index+1)
}
}
return res
}