给你一个未排序的整数数组 nums ,请你找出其中没有出现的最小的正整数。
请你实现时间复杂度为 O(n) 并且只使用常数级别额外空间的解决方案。
示例 1:
输入:nums = [1,2,0]
输出:3
示例 2:
输入:nums = [3,4,-1,1]
输出:2
示例 3:
输入:nums = [7,8,9,11,12]
输出:1
提示:
1 <= nums.length <= 5 * 105
-231 <= nums[i] <= 231 - 1
#include<iostream>
#include<stack>
#include<algorithm>
#include<string>
#include<vector>
using namespace std;
/*
遍历一次数组查当前下标是否和值对应,如果不对应那这个下标就是答案,
否则遍历完都没出现那么答案就是数组长度加1。
*/
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
sort(nums.begin(), nums.end());
int n = nums.size();
int res = 1;
for (int i = 0; i < n; ++i)
{
if (nums[i]>0)
{
if (nums[i] == res)
{
res++;
}
else if (nums[i]>res)
{
break;
}
}
}
return res;
}
};
int main()
{
int a[1000];
int x;
int i = 0;
vector<int> vec;
int target;
while (cin >> a[i])
{
vec.push_back(a[i]);
i++;//注意这里i++对输出结果的影响
x = cin.get();
if (x == ‘\n‘)
break;
}
int ans = Solution().firstMissingPositive(vec);
cout << ans << endl;
system("pause");
return 0;
}
原文:https://www.cnblogs.com/277223178dudu/p/14882817.html