[Leetcode] First missing positive

Source: Internet
Author: User
First missing positive

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

For example,
Given[1,2,0]Return3,
And[3,4,-1,1]Return2.

Your algorithm shold run inO(N) Time and uses constant space.

Algorithm analysis:

Set ~ The number of A. length is placed at the corresponding position of the subscript. Other plural values or values greater than a. length are not processed.

Then traverse a again and find the first default integer.

[Note] processing of repeated numbers and negative numbers; I should be placed in the I-1 position, but if I-1 is also placed in the I-1 position, skip; if it is not a positive number, skip; skip if the number is too large;

The Code is as follows:

 1 public class Solution { 2     public int firstMissingPositive(int[] a) { 3         if(a == null || a.length == 0) return 1; 4         int length = a.length; 5         for(int i = 0; i < length; i++){ 6             if(a[i] > length - 1 || a[i] <= 0 || a[i] == a[a[i] - 1]) continue; 7             int t = a[a[i] - 1]; 8             a[a[i] - 1] = a[i]; 9             a[i] = t;10             i--;11         }12         int positive = 1;13         for(int i = 0; i < length; i++){14             if(a[i] <= 0) continue;15             if(a[i] == positive){16                 positive++;17             }else{18                 return positive;19             }20         }21         return positive;22     }23 }

This question is very good.

 

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.