First Missing Positive

Source: Internet
Author: User

First Missing Positive

Problem:

Given an unsorted integer array, find the first missing positive integer.

Ideas:

A[a[i] [= A[i] Classic applications

My Code:

 Public classSolution { Public intFirstmissingpositive (int[] nums) {        if(nums==NULL|| nums.length==0)return1; intLen =nums.length; inti = 0;  while(I <Len) {            if(Nums[i] <= 0) {i++; }            Else            {                intindex =Nums[i]; if(Index >Len) {Nums[i]= 0; I++; }                Else                {                    if(Nums[index-1] = = index) i++; Else                    {                        intTMP = Nums[index-1]; Nums[index-1] =Nums[i]; Nums[i]=tmp; }                }            }        }         for(intk=0; k<len; k++)        {            if(Nums[k]! = k+1)returnK+1; }        returnLen+1; }    }
View Code

Others code:

//Solution 2:     Public intFirstmissingpositive (int[] A) {//bug 3:when length is 0, return 1;        if(A = =NULL) {            return0; }         for(inti = 0; i < a.length; i++) {            //1:a[i] is in the range; //2:a[i] > 0. //3:the target is different;             while(A[i] <= a.length && a[i] > 0 && a[a[i]-1]! =A[i]) {Swap (A, I, A[i]-1); }        }                 for(inti = 0; i < a.length; i++) {            if(A[i]! = i + 1) {                returni + 1; }        }                returnA.length + 1; }
View Code

The Learning Place:

    • Carefully below this piece of code, each a[i] has a mission, what is called the end of the mission, after the ups and downs of the process A[i] The value of several changes, but a[a[i] [= A[i] succeeded, at this moment the mission is over.
 while (A[i] <= a.length && a[i] > 0 && a[a[i]-1]! = A[i])                {-1);                }
View Code
    • Change a bad habit

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.