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.

分析

本质上是桶排序(bucket sort),每当 A[i]!= i+1 的时候,将A[i]A[A[i]-1]交换,直到无法交换为止,终止条件是 A[i]== A[A[i]-1]

代码

  1. // First Missing Positive
  2. // 时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public:
  5. int firstMissingPositive(vector<int>& nums) {
  6. bucket_sort(nums);
  7. for (int i = 0; i < nums.size(); ++i)
  8. if (nums[i] != (i + 1))
  9. return i + 1;
  10. return nums.size() + 1;
  11. }
  12. private:
  13. static void bucket_sort(vector<int>& A) {
  14. const int n = A.size();
  15. for (int i = 0; i < n; i++) {
  16. while (A[i] != i + 1) {
  17. if (A[i] <= 0 || A[i] > n || A[i] == A[A[i] - 1])
  18. break;
  19. swap(A[i], A[A[i] - 1]);
  20. }
  21. }
  22. }
  23. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/sorting/bucket-sort/first-missing-positive.html