LeetCode ---- First Missing Positive

Source: Internet
Author: User

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.

Analysis:

Thought 1: first sort and then scan the array again .. O (nlgn)

Idea 2: A total of n numbers. For those numbers greater than n, it will not be our first missing positive integer.

It is equivalent that we have n buckets. Each bucket should start from 1 to n, and the first unsatisfied bucket is our result.


Class Solution {public: int firstMissingPositive (int A [], int n) {bucket_sort (A, n); for (int I = 0; I

 
  
N | A [I] = A [A [I]-1]) break; swap (A [I], A [A [I]-1]) ;}}};

 


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.