Leetcode 41. First Missing Positive
阿新 • • 發佈:2019-01-05
array .com inpu get tor span n) nbsp sta
41. First Missing Positive
題目鏈接:https://leetcode.com/problems/first-missing-positive/
Description:
Given an unsorted integer array, find the smallest missing positive integer.Your algorithm should run in O(n) time and uses constant extra space.
Example 1:
Input: [1,2,0] Output: 3
Example 2:
Input: [3,4,-1,1] Output: 2
Example 3:
Input: [7,8,9,11,12] Output: 1
題意:
給出n個無序的數,問缺失的最小正數是多少,要求在O(N)時間內解決問題。
題解:
註意到答案只能在1~n+1之間,那麽我們就可以統計給出的數中在1~n中是否出現,判斷下就好了。
代碼如下:
class Solution { public: int firstMissingPositive(vector<int>& nums) { int n = nums.size(); int vis[n+2]={0};for(int i=0;i<n;i++){ if(nums[i]>=1 && nums[i]<=n) vis[nums[i]]=1; } for(int i=1;i<=n;i++) if(!vis[i]){ return i; } return n+1 ; } };
Leetcode 41. First Missing Positive