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

LeetCode 041 First Missing Positive

时间:2015-02-07 21:36:58      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:

题目要求: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.

 

代码如下:

class Solution {
public:
    int firstMissingPositive(int A[], int n) {

        for (int i = 0, temp = -1; i < n; i++) {
            while (A[i] - 1 >= 0 && A[i] - 1 < n && A[i] - 1 != i) {
                swap(A, i, A[i] - 1);
                if (A[i] == temp) {
                    break;
                }
                else {
                    temp = A[i];
                }
            }
        }
        for (int i = 0; i < n; i++) {
            if (A[i] - 1 != i) {
                return i + 1;
            }
        }
        return n + 1;
    }

private:
    void swap(int A[], int idx1, int idx2) {
        A[idx1] ^= A[idx2];
        A[idx2] ^= A[idx1];
        A[idx1] ^= A[idx2];
    }
};

 

LeetCode 041 First Missing Positive

标签:

原文地址:http://www.cnblogs.com/510602159-Yano/p/4279247.html

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