您的位置:首页 > 其它

Leetcode no. 41

2016-07-09 23:40 190 查看
41. 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.

public class Solution {
public int firstMissingPositive(int[] nums) {
if (nums.length==0) return 1;
for (int i=0; i<nums.length; i++){
while (nums[i]>0 && nums[i]<= nums.length && nums[i]!=i+1){
if (nums[i]== nums[nums[i]-1]) break;
int tmp= nums[nums[i]-1];
nums[nums[i]-1]= nums[i];
nums[i]= tmp;
}
}
for (int i=0; i<nums.length; i++){
if (nums[i]!=i+1) return i+1;
}
return nums[nums.length-1]+1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: