[LeetCode] [Java] First Missing Positive

Source: Internet
Author: User

[LeetCode] [Java] First Missing Positive

Question:

 

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 shocould run in O (n) time and uses constant space.


Question:

Given an unordered integer array, find the first missed positive integer.

For example:

Given[1,2,0]3,

[,-] Returns 2.

The algorithm requires O (n) time complexity and constant space.

Algorithm analysis:

The simplest way is to sort arrays quickly. However, due to the time complexity of O (n), fast sorting is obviously not feasible.

 

Therefore, in order to search for elements, the subscript of the array is used as its index, that is, the elements of the array are exchanged and positive numbers are iPut in i-1The negative number and elements greater than the array length are discarded. In this way, the first nonexistent positive number can be obtained by scanning the array linearly, that is, the first jThe position element is not equal j+1.

 

AC code:

 

Public class Solution {public int firstMissingPositive (int [] A) {// place A positive number to the position of-1, so that 1 is placed at position 0, 2 is placed in the position on the 1st ,.... If (A = null | A. length = 0) return 1; for (int I = 0; i0 & A [A [I]-1]! = A [I]) // here A [A [I]-1]! = A [I] indicates that {int temp = A [A [I]-1] is not exchanged if the condition has been met. A [A [I]-1] = A [I]; A [I] = temp; I -- ;}} for (int I = 0; I

 

 

 

 

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.