`

Leetcode - First Missing Positive

 
阅读更多
[分析]
将各个正数放入相应下标处,使之满足nums[nums[i] - 1] = nums[i],则一遍扫描后值在数组长度范围内的都按序排列了,然后二遍扫描遇到第一个打破秩序的位置i,则 i + 1就是第一个缺失的正数。
[ref]
解析清楚的Code Ganker博客:http://blog.csdn.net/linhuanmars/article/details/20884585
简洁的实现:https://leetcode.com/discuss/24013/my-short-c-solution-o-1-space-and-o-n-time

public class Solution {
    public int firstMissingPositive2(int[] nums) {
        if (nums == null) return 1;
        int N = nums.length;
        for (int i = 0; i < N; i++) {
            while (nums[i] > 0 && nums[i] <= N && nums[nums[i] - 1] != nums[i]) {
                int tmp = nums[nums[i] - 1];
                nums[nums[i] - 1] = nums[i];
                nums[i] = tmp; 
            }
        }
        for (int i = 0; i < N; i++) {
            if (nums[i] != i + 1)
                return i + 1;
        }
        return N + 1;
    }
    public int firstMissingPositive1(int[] nums) {
        if (nums == null) return 1;
        int N = nums.length;
        for (int i = 0; i < N; i++) {
            if (nums[i] > 0 && nums[i] <= N && nums[nums[i] - 1] != nums[i]) {
                int tmp = nums[nums[i] - 1];
                nums[nums[i] - 1] = nums[i];
                nums[i] = tmp; 
                i--;
            }
        }
        for (int i = 0; i < N; i++) {
            if (nums[i] != i + 1)
                return i + 1;
        }
        return N + 1;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics