leetcode:41. First Missing Positive (Java)
転載は出典を明記してください:z_zhaojunのブログの原文の住所の題目の住所First Missing Positive
コード実装(Java):
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.
コード実装(Java):
public class Solution {
public int firstMissingPositive(int[] nums) {
int l = nums.length;
int swap;
for (int i = 0; i < l;) {
swap = nums[i++];
while (swap > 0 && swap <= l && swap != nums[swap - 1]) {
int tmp = nums[swap - 1];
nums[swap - 1] = swap;
swap = tmp;
}
}
for (int i = 0; i < l;) {
if (nums[i] != ++i) {
return i;
}
}
return l + 1;
}
}