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

LeetCode - First Missing Positive

时间:2015-12-25 13:23:04      阅读:126      评论: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.

思路:

不断进行交换,将值为 i 的数字交换到 (i - 1)th 的位置.

package array;

public class FirstMissingPositive {

    public int firstMissingPositive(int[] nums) {
        int n;
        if (nums == null || (n = nums.length) == 0) return 1;
        for (int i = 0; i < n; ++i) {
            int a = nums[i];
            while (a > 0 && a <= n && nums[i] != i + 1 && nums[a - 1] != a) {
                swap(nums, i, a - 1);
                a = nums[i];
            }
        }
        
        int j = 0;
        while (j < n && nums[j] == j + 1){
            ++j;
        }
        return j + 1;
    }
    
    private void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] nums = { 1,1 };
        FirstMissingPositive f = new FirstMissingPositive();
        System.out.println(f.firstMissingPositive(nums));
    }

}

 

LeetCode - First Missing Positive

标签:

原文地址:http://www.cnblogs.com/shuaiwhu/p/5075525.html

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