leetcode 41. First Missing Positive

传送门

41. First Missing Positive

 
 My Submissions
 
  • Total Accepted: 69874
  • Total Submissions: 288517
  • Difficulty: Hard

 

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.

 

Subscribe to see which companies asked this question

Hide Tags
 Array
 
 
题解转自:
http://blog.csdn.net/sbitswc/article/details/31870975
 
桶排序,每次当A[i]!= i的时候,将A[i]与A[A[i]]交换,直到无法交换位置。终止条件是 A[i]== A[A[i]]。
然后i -> 0 到n走一遍就好了。
 
 1 class Solution {
 2 public:
 3     int firstMissingPositive(vector<int>& nums) {
 4         int sz = nums.size();
 5         int i = 0;
 6         
 7         while(i < sz){
 8             if(nums[i] != i + 1 && nums[i] > 0 && nums[i] < sz && nums[i] != nums[ nums[i] - 1 ]) {
 9                 swap(nums[i],nums[ nums[i] - 1 ]);
10             }
11             else{
12                 i++;
13             }
14         }
15         
16         for(i = 0;i < sz;i++){
17             if(nums[i] != i + 1){
18                 return i + 1;
19             }
20         }
21         return sz + 1;
22     }
23 };

 

posted on 2016-07-25 22:06  njczy2010  阅读(166)  评论(0编辑  收藏  举报