标签:
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.
思路:新建一个数组B,然后用A[i]的值作为B的index,即B[A[i]] =1,然后遍历一遍B,寻找B[i]!=1的index,不过貌似我的时间复杂度是O(n),空间也是O(n)啊。。
class Solution { public: int firstMissingPositive(int A[], int n) { vector<int> B; B.resize(n + 1); //cout << "n\t" << n << endl; //printArray(A, n); for(int i = 0; i < n; i++) { if(A[i] <= n && A[i] >0) { // do A[i]‘s value as B‘s index B[A[i]] = 1; } } //printVector(B); for(size_t i = 1; i < B.size(); i++) { if(B[i] != 1) return i; } return n+1; } };
[LeetCode] First Missing Positive
标签:
原文地址:http://www.cnblogs.com/diegodu/p/4285599.html