LeetCode, leetcodeoj

Source: Internet
Author: User

LeetCode, leetcodeoj

Link: First Missing Positive

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

The requirement for this question is to find the first missing positive integer in array A (unordered. Requires O (n) time complexity.

The direct idea of this question is to sort it first, and then traverse it to find the first missing positive integer. However, the time complexity is O (nlogn ).

The question requires O (n) time complexity, so can it be faster? You can consider sorting. Similar to the idea of counting and sorting, apply for an empty array B of the same size, and then specify array, place the number that appears in A in B corresponding to the position of B's lower mark (if the number size exceeds the range of B, it is not processed ), for example, put 5 in B [4. Finally, traverse array B to find the first missing positive integer.

Since the array B applied for above is as big as array A, can we directly use array A instead of array B? Of course, when traversing A, if the number and position do not match, you can switch to the corresponding position.

Time Complexity: O (n)

Space complexity: O (1)

 1 class Solution 2 { 3 public: 4     int firstMissingPositive(int A[], int n) 5     { 6         for(int i = 0; i < n; ++ i) 7             while(A[i] > 0 && A[i] <= n && A[A[i] - 1] != A[i]) 8                 swap(A[i], A[A[i] - 1]); 9         10         for(int i = 0; i < n; ++ i)11             if(A[i] != i + 1)12                 return i + 1;13         14         return n + 1;15     }16 };

Reprinted please note the Source: LeetCode --- 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.