LeetCode-First Missing Positive

没想出来,想到了count sort,但是没想到怎样用常量空间的方法。

看了大神Annie Kim(https://github.com/AnnieKim/LeetCode)的代码,才豁然开朗,

也算有学习和总结到了一条规律:

凡是要求常量空间的题目要尽量利用题目中已有的空间!

这道题目很经典,非常好的面试题。

就算知道了方法以后,实现的时候也还是有一定的技巧的,

每个位置i都需要多次交换,直到A[i] = i + 1为止,不过对于A[i] > n的元素

可以先不管,最后再交换到最后!

 1 class Solution {
 2 public:
 3     int firstMissingPositive(int A[], int n) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         if (n == 0) {
 7             return 1;
 8         }
 9         int i = 0; 
10         while (i < n) {
11             if (A[i] != i + 1 && A[i] > 0 && A[i] <= n && A[A[i] - 1] != A[i]) {
12                 swap(A[i], A[A[i] - 1]);
13             }
14             else {
15                 ++i;
16             }
17         }
18         for (i = 0; i < n; ++i) {
19             if (A[i] != i + 1) {
20                 return (i + 1);
21             }
22         }
23         return n + 1;
24     }
25 };
原文地址:https://www.cnblogs.com/chasuner/p/firstmissingpositive.html