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.

 

方法比较巧,先把所有元素的值-1,重新组织元素使A[i] = i,这样只要找到第一个A[i] != i 的 i。注意要用while循环,for循环的continue是从下一次循环开始的。

 

 1 class Solution {
 2 public:
 3     int firstMissingPositive(int A[], int n) {
 4         int tmp;
 5         for (int i = 0; i < n; ++i) {
 6             A[i]--;
 7         }
 8         int i = 0;
 9         while (i < n) {
10             if (A[i] != i && A[i] >= 0 && A[i] < n && A[i] != A[A[i]]) {
11                 tmp = A[i];
12                 A[i] = A[A[i]];
13                 A[tmp] = tmp;
14             } else {
15                 i++;
16             }
17         }
18         for (int i = 0; i < n; ++i) {
19             if (A[i] != i) {
20                 return i + 1;
21             }
22         }
23         return n + 1;
24     }
25 };

 

相关文章:

  • 2022-01-29
  • 2022-02-24
  • 2021-07-27
  • 2021-08-02
  • 2022-12-23
猜你喜欢
  • 2021-06-08
  • 2022-01-02
  • 2021-07-22
  • 2021-08-09
  • 2021-11-29
  • 2021-10-03
  • 2021-12-31
相关资源
相似解决方案