您的位置:首页 > 其它

Leetcode First Missing Positive

2016-07-19 05:08 435 查看
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.

Difficulty: Hard

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