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.

Similar: 287. Find the Duplicate Number

268. Missing Number

 

 1 public class Solution {
 2     public int firstMissingPositive(int[] nums) {
 3         if (nums.length == 0) return 1;
 4         
 5         int n = nums.length;
 6         int i = 0;
 7         while (i < n) {
 8             if (nums[i] > 0 && nums[i] < n && nums[i] != i && nums[nums[i]] != nums[i]) { // in case duplicate as [1,1]
 9                 int tmp = nums[nums[i]];
10                 nums[nums[i]] = nums[i];
11                 nums[i] = tmp;
12             } else {
13                 i++;
14             }
15         }
16         
17         i = 1;
18         while(i < n) {
19             if (nums[i] != i) {
20                 return i;
21             }
22             i++;
23         }
24         return nums[0] == n ? n+1 : n;
25     }
26 }

 

posted @ 2016-04-20 11:41  Joyce-Lee  阅读(145)  评论(0编辑  收藏  举报