【1日1本LeetCode】#41.First Missing Positive
1日1本のLeetCodeシリーズ
(一)テーマ
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.
(二)問題を解く
(一)テーマ
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.
(二)問題を解く
/* vector , target=1 0 , target +1, target target , target+1; : */
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
sort(nums.begin(),nums.end());
int target = 1;
for(int i = 0 ; i < nums.size() ; i++)
{
if(nums[i]>0)
{
if(nums[i] == target)
{
target++;// +1 , target
}
else if(i>0 &&nums[i]!=nums[i-1])//
{
return target;
}
}
}
return target;// target+1
}
};