Leetcode 41. First Missing Positive

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

First Missing Positive

2. Solution

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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;
}
};

Reference

  1. https://leetcode.com/problems/first-missing-positive/description/
如果有收获,可以请我喝杯咖啡!