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 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| package main
import ( "fmt" )
func firstMissingPositive_0(nums []int) int { hash := make(map[int]bool) for _, num := range nums { hash[num] = true } for i := 1; i <= len(nums); i ++ { if !hash[i] { return i } }
return len(nums) + 1 }
func firstMissingPositive(nums []int) int { n := len(nums) for i := 0; i < n; i ++ { for nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i] { nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1] } } for i := 0; i < n; i ++ { if nums[i] != i + 1 { return i + 1 } }
return n + 1 }
func main() { testCases := []struct { nums []int expected int }{ {[]int{1,2,0}, 3}, {[]int{3,4,-1,1}, 2}, {[]int{7,8,9,11,12}, 1}, } for i, tc := range testCases { fmt.Printf("Test Case %d, Input: nums = %v\n", i+1, tc.nums) result := firstMissingPositive(tc.nums)
if result == tc.expected { fmt.Printf("Test Case %d, Output: %d, PASS\n", i+1, result) } else { fmt.Printf("Test Case %d, Output: %d, FAIL (Expected: %d)\n", i+1, result, tc.expected) } } }
|