首页 > 其他 > 详细

LeetCode41 First Missing Positive****

时间:2015-04-12 22:45:39      阅读:281      评论:0      收藏:0      [点我收藏+]

leetcode41 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.

分析:此题关键O(n)和常量空间的限制。常量空间的话第一可以考虑是不是固定数量的几个变量能搞定;否则可以考虑是不是问题本身已经提供了足够的空间。当然这里O(1)就可以解决。

class Solution {
public:
    int firstMissingPositive(int A[], int n) {
        for(int i = 0; i < n; i++){
            while(A[i] > 0 && A[i] <= n &&  A[A[i]-1] != A[i]){  //  比如1 2 5 6 7    此时的A[2]的5就需要与A[4]交换
                swap(A[i], A[A[i]-1]);
            }
        }
        for(int i = 0; i < n; i++)
            if(A[i] != i+1) return i+1;
        return n+1;
        
    }
};
很多人认为这不是O(N)时间,其实虽然当条件满足,i没有++,但是此时可以是A[A[i]-1]的值变成了A[i],当循环到下标A[i]-1,条件肯定不满足,故还是O(N)时间。当然了本问题没有必要限制数据不重复。。。It is amazing!!

LeetCode41 First Missing Positive****

原文:http://blog.csdn.net/lu597203933/article/details/45014593

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!