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. public class Solution {
  4. public int firstMissingPositive(int[] nums) {
  5. bucket_sort(nums);
  6. for (int i = 0; i < nums.length; ++i)
  7. if (nums[i] != (i + 1))
  8. return i + 1;
  9. return nums.length + 1;
  10. }
  11. private static void bucket_sort(int[] A) {
  12. final int n = A.length;
  13. for (int i = 0; i < n; i++) {
  14. while (A[i] != i + 1) {
  15. if (A[i] < 1 || A[i] > n || A[i] == A[A[i] - 1])
  16. break;
  17. // swap
  18. int tmp = A[i];
  19. A[i] = A[tmp - 1];
  20. A[tmp - 1] = tmp;
  21. }
  22. }
  23. }
  24. }

相关题目

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