LeetCode:First Missing Positive

题目连接html

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 spacespa

寻找数组中缺失的最小正整数code


算法1

首先最容易想到的是:先对数组排序,而后在查找,可是这样不知足线性时间要求。如下代码oj仍是能经过的htm

class Solution {
public:
    int firstMissingPositive(int A[], int n) {
        sort(A, A+n);
        int k = 1;
        for(int i = 0; i < n; i++)
            if(A[i] < k);//为了处理小于1的数 或者 处理连续出现相同的数
            else if(A[i] != k)return k;
            else k++;
        return k;
    }
};


算法2

使用哈希表来记录某个数字是否出现过(固然也可使用bitmap)。这样的话空间复杂度和int的最大值有关blog

class Solution {
public:
    int firstMissingPositive(int A[], int n) {
        unordered_set<int> uset;
        for(int i = 0; i < n; i++)
            if(A[i] > 0)uset.insert(A[i]);
        for(int i = 1; ;i++)
         if(uset.count(i) == 0)return i;
    }
};


算法3

注意到大小为n的数组,缺失的最小正整数必定在范围[1,n+1]内,所以改进一下算法2,可使用大小为n+1的哈希表。空间复杂度是O(n),不符合题意排序

class Solution {
public:
    int firstMissingPositive(int A[], int n) {
        vector<int> hashtable(n+2, 0);//hashtable[i] = 1表示数字i出现过
        for(int i = 0; i < n; i++)
            if(A[i] > 0 && A[i] <= n+1)hashtable[A[i]] = 1;
        for(int i = 1; i <= n+1; i++)
            if(hashtable[i] == 0)return i;
    }
};


算法4ip

上述算法3中,咱们能够用数组自己来充当哈希表。稍微变通一下,在遍历数组的过程当中把数字 i 放在A[i-1]的位置。最后若是A[k] != k+1就说明k+1这个数字没有出现过。因为数组的大小是n,所以若是原始数组中的数字是1,2…n,则最后应该返回n+1。leetcode

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

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

 

 

【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3770051.html

相关文章
相关标签/搜索