41-first Missing Positive

Source: Internet
Author: User

Topic

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.

"Analyze"

1. Because it is disorderly, it is a bit cumbersome to deal with. Consider placing the correct positive number at the correct index position, and then traversing the entire array

2. There are two places that have not been noticed: first, after the current position exchange, also need to judge; Ii. if you solve the first problem (join while), the current value and the value of the interchange will enter the dead loop

Algorithm

v1: A rather shameless approach, sorted first Public classSolution { Public intFirstmissingpositive (int[] nums)        {Arrays.sort (nums); intFlag=1; intI=0;  while(i<nums.length) {if(nums[i]>0) {                if(nums[i]==flag) {Flag++; I++;  while(i<nums.length&&nums[i]==nums[i-1]) I++; }Else                    returnFlag; }ElseI++; }        returnFlag; }}V2: Public classSolution { Public intFirstmissingpositive (int[] nums) {        if(nums==NULL|| Nums.length<1)            return1; intlen=nums.length;  for(inti=0;i<nums.length;i++) {             while(nums[i]!=i+1&&nums[i]>0&&nums[i]<=Len) {                if(nums[i]==nums[nums[i]-1])                     Break; inttemp=Nums[i]; Nums[i]=nums[temp-1]; Nums[temp-1]=temp; }        }         for(inti=0;i<len;i++) {            if(nums[i]!=i+1)                returnI+1; }        returnLen+1; }}

41-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.