码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode:41. First Missing Positive (Java)

时间:2016-03-13 18:05:01      阅读:222      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!