【LeetCode】No.41. First Missing Positive -- Java Version

180 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第20天。

题目链接: leetcode.com/problems/fi…

1. 题目介绍(First Missing Positive)

Given an unsorted integer array nums, return the smallest missing positive integer.

【Translate】: 给定一个未排序的整数数组nums,返回缺失的最小正整数。

You must implement an algorithm that runs in O(n) time and uses constant extra space.

【Translate】: 你必须实现一个运行时间为O(n)的算法,并且使用恒定的额外空间。

【测试用例】:

testcase

【约束】:

constraints

2. 题解

2.1 条件筛选排序

  代码来自lksbos的题解Java 100% fast simple and easy,该题解的关键就在于一开始的条件筛选,筛选的条件首先是当前值要是正数,其次当前值要小于nums数组的长度,因为该题是让我们寻找缺失的最小正整数,那么肯定就是从1、2、3开始往后排,那么如果当前值大于了nums数组的长度,那么就说明它一定超出了我们要寻找的最小正整数的范围,所有可以直接pass,进行下一个;最后则是最关键的一个条件,通过curr != nums[curr-1]来实现基于1的排序,配合swap函数变相将符合条件的数字排序到正确的位置,如[1,2,7,5,3],最后就能排序成[1,2,3,7,5],本来就正确的数字位置不变,这样最后只需再遍历一遍排序好的数组,看一下到哪一位不符合就可以找出缺失的数字。

class Solution {
    public int firstMissingPositive(int[] nums) {
        for(int i = 0; i < nums.length;) {
            int curr = nums[i];
            //in place sorting 1 based index ignoring out of range numbers including 0
			if(curr > 0 && curr < nums.length && curr != nums[curr-1]) 
                swap(nums, i, curr-1);
            else
                i++;
        }
        //check if the number on index i is equal to i + 1 (1 based idxs) if not we have our number
        for(int i = 0; i < nums.length; i++) {
            if(nums[i] != i + 1) {
                return i + 1;
            }
        }
		//if the whole array have the correct numbers the next number is the last pos (nums.length) + 1
        return nums.length + 1;
    }
    
    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

test1