LeetCode First Missing Positive
來源:程序員人生 發布時間:2015-03-09 09:04:25 閱讀次數:3256次
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0]
return 3
,
and [3,4,⑴,1]
return 2
.
Your algorithm should run in O(n) time and uses constant space.
題意:找到第1個最小的正整數。
思路:由于要求不能用到額外的空間,題目有暗示:答案在[1,n+1]之間。每一個位置都試著將這個位置的值換到對應的下標,這樣第1個位置出現不是相應的值的時候就是答案,還有就是要是都能對應,那末n+1就是解
class Solution {
public:
int firstMissingPositive(int A[], int n) {
for (int i = 0; i < n; i++) A[i]--;
for (int i = 0; i < n; i++) {
while (A[i] != i && A[i] >= 0 && A[i] < n) {
if (A[i] == A[A[i]]) break;
swap(A[i], A[A[i]]);
}
}
for (int i = 0; i < n; i++)
if (A[i] != i)
return i + 1;
return n+1;
}
};
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈