首页 > 编程语言 > 详细

leetcode:41. First Missing Positive (Java)

时间:2016-03-13 18:04:42      阅读:207      评论:0      收藏:0      [点我收藏+]

转载请注明出处:z_zhaojun的博客
原文地址
题目地址
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.

代码实现(Java):

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

leetcode:41. First Missing Positive (Java)

原文:http://blog.csdn.net/u012975705/article/details/50878150

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!