448.find-all-numbers-disappeared-in-an-array.go 572 B

1234567891011121314151617181920212223242526272829303132333435
  1. func findDisappearedNumbers(nums []int) (res []int) {
  2. n := len(nums)
  3. for i := 0; i < n; i++ {
  4. if idx := abs(nums[i]) - 1; 0 < nums[idx] {
  5. nums[idx] = -nums[idx]
  6. }
  7. }
  8. for i := 0; i < n; i++ {
  9. if 0 < nums[i] {
  10. res = append(res, i+1)
  11. }
  12. }
  13. return
  14. }
  15. func abs(x int) int {
  16. if x < 0 {
  17. return -x
  18. }
  19. return x
  20. }
  21. func findDisappearedNumbersOn(nums []int) (res []int) { // O(n) extra space
  22. n := len(nums)
  23. set := make([]bool, n+1)
  24. for _, i := range nums {
  25. set[i] = true
  26. }
  27. for i := 1; i <= n; i++ {
  28. if !set[i] {
  29. res = append(res, i)
  30. }
  31. }
  32. return
  33. }