[LeetCode] 41. First Missing Positive

[LeetCode] 41. First Missing Positive

题目

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

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

Example 1:

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

思路

方法一:哈希

总共有 n 个数,所以第一个缺失的正整数一定在[1, n] 之间,所以只用考虑在 [1, n] 的数,用一个数组 a , a[i] = true, 表示 i 这个正整数没有缺失。找第一个使 a[i] = false 的就是答案。

其实可以不用 a 这个数组, 可以用原数组数的正负来表示 false 和 true, 因为非正数对结果没有影响,可以先把原数组所有的非正数(包括0)变为 n+1, 这样数组就变为非负的,如果一个 [1, n] 中的数 x 存在,那么就把 a[x] 变为负的,最后找第一个为正数的位置就是答案。

方法二:

将元素置换到原来的位置上。([1 2 3 ... N])

https://leetcode-cn.com/problems/first-missing-positive/solution/que-shi-de-di-yi-ge-zheng-shu-by-leetcode-solution/

代码

class Solution {
public:
    int firstMissingPositive(vector<int>& nums) {
        int n = nums.size();
        for (int& num: nums) {
            if (num <= 0) {
                num = n + 1;
            }
        }
        for (int i = 0; i < n; i++) {
            int num = abs(nums[i]);
            if (num <= n) {
                nums[num-1] = -abs(nums[num-1]);
            }
        }
        for (int i = 0; i < n; i++) {
            if (nums[i] > 0) {
                return i + 1;
            }
        }
        return n + 1;
    }
};
欢迎转载,转载请注明出处!
原文地址:https://www.cnblogs.com/huihao/p/15435157.html