题目

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. 排序是 nlogn, 没有其他想法了

2. 参考别人思路. 将 A[i] 月 A[A[i]] 替换, 第二遍 PASS 检查 A[i] == i

 

代码

class Solution {
public:
    int firstMissingPositive(int A[], int n) {
        if(n == 0)
            return 1;
            
		for(int i = 0; i < n; i ++) {
		//	cout << A[i] << endl;
			if(A[i] == i+1 || A[i] <= 0 || A[i] >= n) {
				continue;
			}else {
				swap(A[i], A[A[i]-1]);
				//cout << A[i] << A[A[i]-1] << endl;
				if(A[i] >= 1 && A[i] != A[A[i]-1])
					i--;
			}
		}
		for(int i = 0; i < n; i ++) {
			if(A[i] != i+1)
				return i+1;
		}
		return n+1;
    }
};

  

相关文章:

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