[LeetCode][JavaScript]First Missing Positive

來源:互聯網
上載者: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/

 

 

 

 

 

 

要求線性時間複雜度,就不能排序了,常數的空間複雜度,不能用雜湊表。

要找出第一個未出現的數字。

給定的數組大小為n,結果不可能超過n。

遍曆數組,把小於等於n的正數放到數組中下標為n-1的位置。

這邊需要遞迴,因為被交換的數也可能也需要放到指定的位置。

最後遍曆交換過順序的數組,如果某個位置(nums[i])的值不等於i+1,i+1就是要求的結果。

 1 /** 2  * @param {number[]} nums 3  * @return {number} 4  */ 5 var firstMissingPositive = function(nums) { 6     for(var i = 0; i < nums.length; i++){ 7         move(i); 8     } 9     for(i = 0; i < nums.length; i++){10         if(nums[i] !== i + 1){11             return i + 1;12         }13     }14     return nums[i - 1] ? nums[i - 1] + 1 : 1;15 16     function move(i){17         var tmp;18         if(nums[i] > 0 && nums[i] <= nums.length && nums[nums[i] - 1] !== nums[i]){19             tmp = nums[nums[i] - 1];20             nums[nums[i] - 1] = nums[i];21             nums[i] = tmp;22             move(i);23         }24     }25 };

 

 

 

[LeetCode][JavaScript]First Missing Positive

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.