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.遍历数组,如果发现当前数组合理则和正确位置上的数字比较
2.如果相同跳过,否则交换.下个循环仍从当前位置进行.
3.第二次遍历验证即可
public int firstMissingPositive(int[] nums) {
for (int i = 0; i < nums.length; ) {
int now = nums[i];
if (now <= 0 || now > nums.length || now == i + 1) { i++; continue;}//忽略情况
int ex = nums[now - 1];//正确位置上的数字
//两数字相等
if (ex == now) {i++; continue;}
//两数不相等则交换两数字
if (ex != now) {
nums[i] = ex;
nums[now - 1] = now;
}
}
for (int i = 0; i < nums.length; i++) {
if (nums[i] != i + 1) {
return i + 1;
}
}
return nums.length + 1;
}
思考:
由于题中起始值1是给定的,所以可以达到这样的效果.
可应用于判断带序号的结果是否缺失的场景中.