题目:
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.
解决:
正负来来记录,值映射到位置。
public class Solution {
public int firstMissingPositive(int[] A) {
for (int i=0; i < A.length; i++){
if (A[i]<=0) A[i]=(A.length+2);//把0与负mo去
}
for (int i=0;i<A.length;i++){
if (Math.abs(A[i])<A.length+1){//把0与负mo去
int cur = Math.abs(A[i])-1;
A[cur] = -Math.abs(A[cur]);//用正负来记录,值映射到位置
}
}
for (int i=0; i < A.length; i++)
if (A[i]>0) return i+1;//没有映射到的位置就是缺的数
return A.length+1;
}
}
本文介绍了一种在未排序整数数组中查找第一个缺失正整数的算法,该算法运行时间为O(n),且使用常数空间。通过将数值映射到数组位置,并利用正负标志来标记出现过的数值,实现高效查找。
270

被折叠的 条评论
为什么被折叠?



