41-First Missing Positive

Description
Given an unsorted integer array, find the smallest missing positive integer.


Example 1:

Input: [1,2,0]
Output: 3

Example 2:

Input: [3,4,-1,1]
Output: 2

Example 3:

Input: [7,8,9,11,12]
Output: 1

Note:
Your algorithm should run in O(n) time and uses constant extra space.


问题描述
给定一个未排序的整数数组,返回最小的缺失正整数


问题分析

若是排好序的正整数数组,为[1, 2, 3, 4, 5…],即i = n - 1(i为下标,n为元素值)

那么我们通过将”错位”的元素通过swap转换到它对应的位置,然后扫描数组就可以了

看一个例子,[1, 2, 0]

1已就位,2已就位,0跳过

从左到右扫描数组,发现只有下标为2处未就位,返回2 + 1,即3


解法

class Solution {
    public int firstMissingPositive(int[] nums) {
        int len = nums.length, i = 0;
        /*
        第一个if的三种情况分别为
        nums[i] <= 0, 非正数
        nums[i] == i + 1, 已就位
        nums[i] > len,元素值太大,无法找到合适的位置就位
        第二个表示元素值未就位,通过swap进行替换,归位
        第三个表示有重复元素,跳过即可
        */
        while(i < len){
            if(nums[i] <= 0 || nums[i] == i + 1 || nums[i] > len)   i++;
            else if(nums[nums[i] - 1] != nums[i])   swap(nums, i, nums[i] - 1);
            else    i++;
        }

        i = 0;
        while(i < len && nums[i] == i + 1)  i++;

        return i + 1;
    }
    public void swap(int[] nums, int a, int b){
        int temp =  nums[a];
        nums[a] = nums[b];
        nums[b] = temp;
    }
}

猜你喜欢

转载自blog.csdn.net/LaputaFallen/article/details/79966835