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

LeetCode First Missing Positive

时间:2014-12-10 14:03:26      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   on   

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.

解题思路:数组总共有n个数,若都是连续的,最大的数是n,也就是说返回的值最大为n+1,遍历数组,如果当前的数num[i],

如果num[i]<=0或者num[i]超过了n,则第一个丢掉的整数必然在num[i]的前面,将num[i]和num[n-1]互换,n--;

如果1<=num[i]<=n,表明这个数可能是好的,将他放在正确的位置swap(num[i],num[num[i]-1])

如果num[i]==i+1,则表明该数字在正确的位置,i++

class Solution {
public:
    int firstMissingPositive(int A[], int n) {
        int m = n;
        for(int i=0;i<m;i++)
        {
            if(A[i] == i+1)continue;
            else
            {
                if(A[i] > m || A[i] == 0 || A[i] < 0 || A[i] <= i)
                {
                    if(i==m-1)
                        return m;
                    swap(A[i],A[m-1]);
                    m--;
                    i--;
                }
                else
                {
                    if(A[i] == A[A[i]-1])
                    {
                        swap(A[i],A[m-1]);
                        m--;
                        i--;
                    }
                    else
                    {
                        swap(A[i],A[A[i]-1]);
                        i--;
                    }
                }
            }
        }
        return m+1;
        
    }
};

 

LeetCode First Missing Positive

标签:style   blog   io   ar   color   os   sp   for   on   

原文地址:http://www.cnblogs.com/55open/p/4155143.html

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