文章作者:Tyan
博客:noahsnail.com ?|? CSDN ?|? 簡書
1. Description
2. Solution
- Version 1
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int x = 0;
for(int i = 1; i <= nums.size(); i++) {
for(int j = 0; j < nums.size(); j++) {
x = i ^ nums[j];
if(x == 0) {
break;
}
}
if(x != 0) {
return i;
}
}
return nums.size() + 1;
}
};
- Version 2
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int index = 0;
int size = nums.size();
for(int i = 0; i < nums.size(); i++) {
if(nums[i] == i + 1) {
continue;
}
if(nums[i] > 0 && nums[i] <= size && nums[nums[i] - 1] != nums[i]) {
swap(nums[nums[i] - 1], nums[i]);
i--;
}
}
for(int i = 0; i < nums.size(); i++) {
if(nums[i] != i + 1) {
index = i;
break;
}
index++;
}
return index + 1;
}
private:
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
};