Leetcode 41: First Missing Positive

Given an unsorted integer array, find the first missing positive integer.

For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.

Your algorithm should run in O(n) time and uses constant space.

 

 1 public class Solution {
 2     public int FirstMissingPositive(int[] nums) {
 3         for (int i = 0; i < nums.Length; i++)
 4         {
 5             while (nums[i] > 0 && nums[i] <= nums.Length && nums[nums[i] - 1] != nums[i])
 6             {
 7                 var tmp = nums[nums[i] - 1];
 8                 nums[nums[i] - 1] = nums[i];
 9                 nums[i] = tmp;
10             }
11         }
12         
13         for (int i = 0; i < nums.Length; i++)
14         {
15             if (nums[i] != i + 1)
16             {
17                 return i + 1;
18             }
19         }
20         
21         return nums.Length + 1;
22     }
23 }

 

posted @ 2018-01-22 09:50  逸朵  阅读(111)  评论(0编辑  收藏  举报