题目要求:First Missing Positive

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.

 

代码如下:

class Solution {
public:
    int firstMissingPositive(int A[], int n) {

        for (int i = 0, temp = -1; i < n; i++) {
            while (A[i] - 1 >= 0 && A[i] - 1 < n && A[i] - 1 != i) {
                swap(A, i, A[i] - 1);
                if (A[i] == temp) {
                    break;
                }
                else {
                    temp = A[i];
                }
            }
        }
        for (int i = 0; i < n; i++) {
            if (A[i] - 1 != i) {
                return i + 1;
            }
        }
        return n + 1;
    }

private:
    void swap(int A[], int idx1, int idx2) {
        A[idx1] ^= A[idx2];
        A[idx2] ^= A[idx1];
        A[idx1] ^= A[idx2];
    }
};

 

相关文章:

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