[Leetcode] [JavaScript] First Missing Positive

Source: Internet
Author: User

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

https://leetcode.com/problems/first-missing-positive/

Requires linear time complexity, it can not be sorted, the spatial complexity of the constant, can not be used in a hash table.

To find the first number that does not appear.

Given an array size of n, the result cannot be more than N.

Iterate through the array, placing a positive number less than or equal to n in the position labeled N-1 in the array.

Recursion is required here, as the number of interchanges may also need to be placed in the specified position.

The last traversal of an array of swap orders, if the value of a location (Nums[i]) is not equal to i+1,i+1, is the required result.

1 /**2 * @param {number[]} nums3 * @return {number}4  */5 varFirstmissingpositive =function(nums) {6      for(vari = 0; i < nums.length; i++){7 move (i);8     }9      for(i = 0; i < nums.length; i++){Ten         if(Nums[i]!== i + 1){ One             returni + 1; A         } -     } -     returnNUMS[I-1]? NUMS[I-1] + 1:1; the  -     functionMove (i) { -         vartmp; -         if(Nums[i] > 0 && nums[i] <= nums.length && nums[nums[i]-1]!==Nums[i]) { +TMP = Nums[nums[i]-1]; -Nums[nums[i]-1] =Nums[i]; +Nums[i] =tmp; A move (i); at         } -     } -};

[Leetcode][javascript]first Missing Positive

Related Article

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.