class Solution { public: int firstMissingPositive(vector<int>& nums) { int n = nums.size(); for (int i = 0; i < n; ++i) { while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) { swap(nums[i], nums[nums[i] - 1]); } } for (int i = 0;...
classSolution {public:intfirstMissingPositive(intA[],intn) {if(n ==0)return1;//if A[i] is negative, i+1 exists in original A//partition, non-negative onlyintlow =0;inthigh = n-1;intend = n-1;while(low <=high) {while(low <= high && A[low] >0) low++;//to here,//case...
int firstMissingPositive(vector<int>& nums) { int n = nums.size(); for(int i = 0; i < n; i++){ while(nums[i] != i + 1){ if(nums[i] <= 0 || nums[i] > n || nums[i] == nums[nums[i]-1]) break; swap(nums[i], nums[nums[i]-1]); } } for(int i = 0; ...
代码2(直接在原数组上进行交换, 空间代价为o(1)) classSolution {public:intfirstMissingPositive(vector<int>&nums) {if(nums.empty())return1; auto begin=getFirstPositivePos(nums);if(*begin <0)return1;for(auto it = begin; it !=nums.end(); ) { auto realPos= begin + *it -1;if(realPo...
class Solution { public: int firstMissingPositive(vector<int>& nums) { bucket_sort(nums); for(int i = 0; i < nums.size(); ++i) { if(nums[i] != i + 1) { return i + 1; } } return nums.size() + 1; } private: void bucket_sort(vector<int>& nums) { for(int i = 0...
First Missing Positive 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.
https://leetcode-cn.com/problems/first-missing-positive/ Given an unsorted integer array, find the smallest missing positive integer. 题意 给你一个未排序的整数数组,请你找出其中没有出现的最小的正整数 。你的算法的时间复杂度应为O(n),并且只能使用常数级别的额外空间。
*/publicintfirstMissingPositive(int[]nums){for(inti=0;i<nums.length;i++){if(nums[i]!=i+1){// swap nums[i] with nums[nums[i] - 1]intcur=nums[i]-1;if(cur>=0&&cur<nums.length&&nums[cur]!=nums[i]){inttemp=nums[i];nums[i]=nums[cur];nums[cur]=temp;// 交换完以后的数字...
https://leetcode-cn.com/problems/first-missing-positive/ Given an unsorted integer array, find the smallest missing positive integer. 题意 给你一个未排序的整数数组,请你找出其中没有出现的最小的正整数 。你的算法的时间复杂度应为O(n),并且只能使用常数级别的额外空间。
classSolution(object):deffirstMissingPositive(self,nums):""":type nums:List[int]:rtype:int""" n=len(nums)foriinrange(n):# print nums[i],i+1,nums[nums[i]-1]whilenums[i]>0and nums[i]<=n and nums[i]!=i+1and nums[i]!=nums[nums[i]-1]:nums[nums[i]-1],nums[i]=nums[...