https://leetcode.com/problems/first-missing-positive/
Given an unsorted integer array, find the smallest missing positive integer.
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
Note:
Your algorithm should run in O(n) time and uses constant extra space.
代码:
class Solution { public: int firstMissingPositive(vector<int>& nums) { sort(nums.begin(), nums.end()); int n = nums.size(); int temp = n + 1; for(int i = 0; i < n; i ++) { if(nums[i] >= 0) { temp = i; break; } } if(temp == n + 1) return 1; else { map<int, int> mp; for(int i = temp; i < n; i ++) mp[nums[i]] ++; for(int i = 1; i <= nums[n - 1]; i ++) { if(mp[i] == 0) return i; } return nums[n - 1] + 1; } } };