LEETCODE41 First Missing positive****

Source: Internet
Author: User

LEETCODE41 First Missing Positive

Topic:

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

Analysis: The limit of the key O (n) and the constant space for this topic. Constant space words First can be considered is not a fixed number of variables can be done, otherwise you can consider whether the problem itself has provided enough space. Of course here O (1) can be solved.

Class Solution {public:    int firstmissingpositive (int. a[], int n) {for        (int i = 0; i < n; i++) {while            (A[i] & Gt 0 && A[i] <= n &&  a[a[i]-1]! = A[i]) {  //  For example 1 2 5 6 7    this time a[2] 5 will need to swap swap with a[4]                (A[i] , A[a[i]-1]);            }        }        for (int i = 0; i < n; i++)            if (a[i]! = i+1) return i+1;        return n+1;}            ;
Many people think this is not O (N) time, in fact, although the condition is satisfied, I do not have + +, but at this point can be a[a[i]-1] value into the a[i], when the loop to subscript a[i]-1, the condition is certainly not satisfied, it is still O (N) time. Of course, there is no need to limit data duplication in this issue ... It is amazing!!

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