您的位置:首页 > 其它

First Missing Positive_Leetcode_#41

2016-09-13 11:24 399 查看
1 题目

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.

Subscribe to see which companies asked this question

2 解法

public class Solution {
public int firstMissingPositive(int[] nums) {
int i = 0;
for(; i < nums.length;){
if((nums[i] == i+1) || nums[i] <= 0 || nums[i] > nums.length){
++i;
}else if(nums[i] != nums[nums[i]-1]){
swap(nums, i, nums[i]-1);
}else{
++i;
}
}
i = 0;
while(i<nums.length && nums[i] == i+1) ++i;
return i + 1;
}

public void swap(int[] nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法