版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Neo233/article/details/84259792
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0] Output: 3
Example 2:
Input: [3,4,-1,1] Output: 2
Example 3:
Input: [7,8,9,11,12] Output: 1
Note:
Your algorithm should run in O(n) time and uses constant extra space.
这个题是查找第一个最小的正整数。
public class Solution {
public int firstMissingPositive(int[] nums) {
if (nums == null || nums.length == 0) // 防止越界
return 1;
for (int i = 0; i < nums.length; i++) {
// nums[i] - 1 < nums.length 超出范围不交换 nums[i] != nums[nums[i] - 1] 相等不交换
while (nums[i] > 0 && nums[i] != i + 1 && nums[i] - 1 < nums.length && nums[i] != nums[nums[i] - 1]) {
swap(nums, i, nums[i] - 1);
}
}
for (int i = 0; i < nums.length; i++) {
if (nums[i] != i + 1) {
return i + 1; // 第一个不相等就返回
}
}
return nums[nums.length - 1] + 1; // 数组交换后是有序正数,就返回最大 + 1
}
public void swap(int[] nums, int i, int j) {
nums[i] = nums[i] ^ nums[j];
nums[j] = nums[i] ^ nums[j];
nums[i] = nums[i] ^ nums[j];
}
}