Java for Leetcode 041 first Missing Positive

Source: Internet
Author: User

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

Problem solving idea One:

Just see the topic when feel not start, and then carefully understand test instructions, need to find first missing positive integer, only need to find the only one, so we can open a Boolean array, storage I exist, Java implementation is as follows:

public int firstmissingpositive (int[] nums) {boolean[] num=new boolean[nums.length + 1];        for (int i = 0; i < nums.length; i++)             if (Nums[i] > 0&&nums[i] <= nums.length)            num[nums[i]-1] = t Rue;        for (int i = 0; i < num.length; i++)            if (!num[i])                return i+1;        return 0;    }

Two: The use of bool array will have O (N) space complexity, the direct use of the Exchange method can be avoided, Java implementation is as follows:

static public int firstmissingpositive (int[] nums)  {       if (nums.length==0)       return 1;        for (int i = 0; i < nums.length;) {            if (Nums[i] >= 0 &&nums[i] < nums.length &&nums[i]! = i && nums[i]! = Nums[nums[i]]) { C5/>int Temp=nums[i];            Nums[i]=nums[nums[i]];            nums[temp]=temp;            }            else i++;        }        for (int i = 1; i < nums.length; ++i)            if (nums[i]! = i)                return i;        return Nums[0] = = Nums.length? Nums.length + 1:nums.length;    }

Java for Leetcode 041 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.