码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] First Missing Positive

时间:2014-06-13 13:16:42      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   java   http   

Questions:

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.

 

bubuko.com,布布扣
 1 public int firstMissingPositive(int[] A) {
 2         int n=A.length;
 3         for(int i=0;i<n;){
 4             if((A[i]!=i+1)&&A[i]>=1&&A[i]<=n&&A[A[i]-1]!=A[i]){
 5                 int temp=A[A[i]-1];
 6                 A[A[i]-1]=A[i];
 7                 A[i]=temp;
 8             }else
 9                 i++;
10         }
11         for(int i=0;i<n;i++){
12             if(A[i]!=i+1){
13                 return i+1;
14             }
15         }
16         return n+1;
17     }
bubuko.com,布布扣

 

这道题我觉得好tricky啊。。。。。。看别人答案都看了好久。。。

觉得还得再消化。。。

该题思路是:

在遍历数组的过程中把数字 i+1 放在A[i]的位置。最后如果A[k] != k+1就说明k+1这个数字没有出现过。由于数组的大小是n,因此如果原始数组中的数字是1,2…n,则最后应该返回n+1。

还需要注意的是if中判断条件:A[i] != A[A[i]-1];即如果某个位置A[i]已经放置了i+1或者数字A[i]即将要放入的位置(A[A[i]-1])原本就是A[i],则跳过。这样可以避免出现死循环(如数组[1,2]和[1,1])

以(3,4,-1,1)来跑改程序:

(  3,  4,  -1,  1)

( -1,  4,  3,  1)

(  1, -1,  3,  4)

 

[Leetcode] First Missing Positive,布布扣,bubuko.com

[Leetcode] First Missing Positive

标签:style   class   blog   code   java   http   

原文地址:http://www.cnblogs.com/wolohaha/p/3781113.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!