Advertisement
Guest User

Untitled

a guest
Mar 26th, 2019
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.86 KB | None | 0 0
  1. /*
  2. Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
  3.  
  4. For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
  5.  
  6. You can modify the input array in-place.
  7. */
  8.  
  9. func solution(_ array: [Int]) -> Int {
  10. guard let max = array.max(), max > 0 else { return 1 }
  11. let count = array.count
  12.  
  13. var temp = Array(repeating: 0, count: max + 1)
  14.  
  15. for j in (0..<count) {
  16. let value = array[j]
  17. if value > 0 {
  18. temp[value] = -1 // marked
  19. }
  20. }
  21.  
  22. for i in (1...max) {
  23. if temp[i] == 0 { // found
  24. return i
  25. }
  26. }
  27. return max + 1
  28. }
  29.  
  30. var input = [3, 4, -1, 1]
  31. let output = solution(input)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement