您的位置:首页 > 其它

【leetcode】Array——First Missing Positive(41)

2016-03-19 21:24 477 查看
题目:

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:Bit Manipulation 受之前一道题目的启发Contains Duplicate(217)

用一个byte数组作为标记位,每个byte可以标记8个数字。遍历nums,并标记出现的正整数,然后从低位开始判断,第一个缺少的正整数。

同样这种方法存在缺陷就是byte数组的长度:按理应该是(2^32)/8

代码1:

public int firstMissingPositive(int[] nums) {
byte[] mark = new byte[150000];
mark[0]|=1;//set 0 mark,方便后续分析
for(int i : nums){
if(i>0){
int byteBlock = i/8;//确定i在第几个byte里面
int byteIndex = i%8;//确定i在byte中具体的位置
mark[byteBlock]|=1<<byteIndex;//把i在byte[]中的标记位设置1
}
}

for(int i=0;i<mark.length;i++){
if(mark[i]!=255){ //如果为255,说明btye中标记位全部为1,如果不是255,说明存在0
for(int j=0;j<=7;j++){
if(mark[i]!=(mark[i]|(1<<j))){//找到具体的低位的0
return (j+8*i);
}
}
}
}
return -1;
}


思路2:从leetcode上看到的。把读取到的正整数放到对应的位置

【3,4,-1,1】=>【1,-1,3,4】 然后找到第一个不对应的元素即可。

见leetcode链接:https://leetcode.com/discuss/24013/my-short-c-solution-o-1-space-and-o-n-time

代码2:

class Solution
{
public:
int firstMissingPositive(int A[], int n)
{
for(int i = 0; i < n; ++ i)
while(A[i] > 0 && A[i] <= n && A[A[i] - 1] != A[i])
swap(A[i], A[A[i] - 1]);

for(int i = 0; i < n; ++ i)
if(A[i] != i + 1)
return i + 1;

return n + 1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: