[LeetCode] 41. First Missing Positive
[Question]
Given an unsorted integer array, find the first missing positive integer.
For example,
Given[1,2,0]
Return3
,
And[3,4,-1,1]
Return2
.
Your algorithm shocould run in O (n) time and uses constant space.
[Analysis]
Similar to bucket sorting.
Every time A [I]! = I + 1, that is, A [I] is not in the correct position and needs to be switched to the corresponding position in the sorting array.
Exchange A [I] with A [A [I]-1] until the exchange fails.
[Code]
/********************************** Date: * Author: SJF0115 * Subject: 41. first Missing Positive * Source: https://oj.leetcode.com/problems/first-missing-positive/* result: AC * Source: LeetCode * blog: * *********************************/# include
Using namespace std; class Solution {public: int firstMissingPositive (int A [], int n) {if (A = NULL | n <= 0) {return 1 ;} // if // switch to the position that should be in the sorting array for (int I = 0; I <n; I ++) {// exchange until the while (A [I]! = I + 1) {// whether to exchange if (A [I] <= 0 | A [I]> n | A [I] = I + 1 | A [I] = A [A [I]-1]) {break;} // if // exchange int tmp = A [I]; A [I] = A [tmp-1]; A [tmp-1] = tmp ;} // while} // for // First Missing Positive for (int I = 0; I <n; I ++) {if (A [I]! = I + 1) {return I + 1;} // if} // for return n + 1 ;}; int main () {Solution solution; int A [] = {1, 1}; cout <
[Analysis 2]
<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink">
VcD4KPHA + CszixL + keys/brD1eK49szixL/keys + keys/keys + zcrHo7o8L3A + keys/aOsvavL/keys + keys/ bHpyajD6KOsyOe5 + 9P2tb3Su7j2QVtpXcrH1f3K/logs/JoaM8bGk + logs + tPrC67b + ob88l21_pgo8cd48chjlignsyxnzpq = "brush: java; "> class Solution {public: int firstMissingPositive (int A [], int n) {if (A = NULL | n <= 0) {return 1 ;} // if int impossValue = n + 2; // first run, turn every negetive value into an impossible positive value // make every value in A is positive for (int I = 0; I <n; I ++) {if (A [I] <= 0) {A [I] = impossValue;} // if} // for // second run, make A [] as a hash table, A [I] indicate the presence of I + 1 // the way is that, if k in [1, n] is in A [], then turn A [k-1] to negetive for (int I = 0; I <n; I ++) {int value = abs (A [I]); if (value <= n) {A [value-1] =-abs (A [value-1]);} // if} // for // third run, if A [I] is positive, from step 2, we know that I + 1 is missing. for (int I = 0; I <n; I ++) {if (A [I]> 0) {return I + 1 ;} // if} // for // all int from 1 to n is present, then return n + 1 return n + 1 ;}};