原地哈希,置换元素【还是标程写的简洁QAQ】
class Solution {
boolean judge(int num, int len, int index) {
if (num >= 1 && num <= len && num != index) {
return true;
}
return false;
}
public int firstMissingPositive(int[] nums) {
int len = nums.length;
int flag = 0;
for (int i = 0; i < len; i++) {
if (judge(nums[i], len, i +1)) {
if (judge(nums[nums[i] - 1], len, nums[i])) {
flag = nums[nums[i] - 1];
}
nums[nums[i] - 1] = nums[i];
while (flag != 0) {
int temp = nums[flag - 1];
nums[flag - 1] = flag;
if (judge(temp, len, flag)) {
flag = temp;
} else {
flag = 0;
}
}
}
}
for (int i = 0; i < len; i++) {
if (nums[i] != i + 1) {
return i + 1;
}
}
return len + 1;
}
}
标程
class Solution {
public int firstMissingPositive(int[] nums) {
int n = nums.length;
for (int i = 0; i < n; ++i) {
while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) {
int temp = nums[nums[i] - 1];
nums[nums[i] - 1] = nums[i];
nums[i] = temp;
}
}
for (int i = 0; i < n; ++i) {
if (nums[i] != i + 1) {
return i + 1;
}
}
return n + 1;
}
}
2022/3/10用标记法完成
class Solution {
public int firstMissingPositive(int[] nums) {
int n = nums.length;
for(int i = 0;i < n;i++) {
if(nums[i] <= 0) {
nums[i] = n + 1;
}
}
for(int i = 0;i < n;i++) {
int temp = Math.abs(nums[i]);
if(temp <= n && temp >= 1 && nums[temp - 1] > 0) {
nums[temp - 1] = -nums[temp - 1];
}
}
for(int i = 0;i < n;i++) {
if(nums[i] > 0) {
return i + 1;
}
}
return n + 1;
}
}