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 ; } };