码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 41:First Missing Positive Number

时间:2015-06-10 15:39:47      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:

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) {
        for(int i=0;i<nums.length;i++){
            if(nums[i]>0&&nums[i]<nums.length&&nums[i]!=nums[nums[i]-1]){
                int temp=nums[nums[i]-1];
                nums[nums[i]-1]=nums[i];
                nums[i]=temp;
                i--;
            }
            
        }
        for(int j=0;j<nums.length;j++){
            if(nums[j]!=j+1)
            return j+1;
        }
        return nums.length+1;
    }
}
View Code

 

LeetCode 41:First Missing Positive Number

标签:

原文地址:http://www.cnblogs.com/gonewithgt/p/4566114.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!