Leetcode First Missing Positive

Source: Internet
Author: User

The original title link is here: https://leetcode.com/problems/first-missing-positive/

Two times scan, first time swap a[i] and it corresponds to the position element A[a[i]-1].

The second time to find if there is a[i]! = i+1, if any, return to i+1, if not, return a.length+1.

Note: The first scan when the swap condition is a[i] greater than 0 and less than equal to A.length, so a[i]-1 have a corresponding position, and exclude a[i] = = A[a[i]-1] Situation, that is, two points are the same, do not need swap, otherwise trapped infinite.

When doing this swap, pay attention to whether the swap is the same and will cause infinite loop.

i--is guaranteed after swap I return to the original position.

AC Java:

1  Public classSolution {2      Public intFirstmissingpositive (int[] A) {3         if(A = =NULL|| A.length = = 0){4             return1;5         }6         //First iteration, swap a[i] to its corresponding position a[a[i]-1]7          for(inti = 0; i<a.length; i++){8             if(a[i]>0 && a[i]<=a.length && a[i]!=a[a[i]-1]){9Swap (A, I, a[i]-1);Teni--; One             } A         } -         //Second Iteration, return i+1 if a[i]! = i+1 -          for(inti = 0; i<a.length; i++){ the             if(A[i]! = i+1){ -                 returnI+1; -             } -         } +         //All correspond, return a.length+1 -         returnA.length + 1; +     } A      Public voidSwapint[] A,intIintj) { at         inttemp =A[i]; -A[i] =A[j]; -A[J] =temp; -     } -}

Leetcode First Missing Positive

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.