题目链接:https://leetcode.com/problems/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.
思路:
让数组中的数”坐在“这个数对应的下标上,比如1应该放在第一个位置,4应该放在第四个位置。
算法:
public int firstMissingPositive(int[] nums) { for (int i = 0; i < nums.length;) { //如果nums[i]不在它应该在的位置,则和它应该在的位置的数互换 if (nums[i] != (i + 1) && nums[i] > 0 && nums[i] <= nums.length && nums[i] != nums[nums[i] - 1]) { int tmp = nums[nums[i] - 1]; nums[nums[i] - 1] = nums[i]; nums[i] = tmp; } else { i++; } } for (int i = 0; i < nums.length; i++) { if (nums[i] != i + 1) { return i + 1; } } return nums.length + 1; }