LEETCODE41 First Missing Positive
Topic:
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 should run in O(n) time and uses constant space.
Analysis: The limit of the key O (n) and the constant space for this topic. Constant space words First can be considered is not a fixed number of variables can be done, otherwise you can consider whether the problem itself has provided enough space. Of course here O (1) can be solved.
Class Solution {public: int firstmissingpositive (int. a[], int n) {for (int i = 0; i < n; i++) {while (A[i] & Gt 0 && A[i] <= n && a[a[i]-1]! = A[i]) { // For example 1 2 5 6 7 this time a[2] 5 will need to swap swap with a[4] (A[i] , A[a[i]-1]); } } for (int i = 0; i < n; i++) if (a[i]! = i+1) return i+1; return n+1;} ;
Many people think this is not O (N) time, in fact, although the condition is satisfied, I do not have + +, but at this point can be a[a[i]-1] value into the a[i], when the loop to subscript a[i]-1, the condition is certainly not satisfied, it is still O (N) time. Of course, there is no need to limit data duplication in this issue ... It is amazing!!
LEETCODE41 First Missing positive****