[牛客网-Leetcode] #数组 较难 first-missing-positive

第一个缺失的正整数 first-missing-positive

题目描述

给出一个无序的整数型数组,求不在给定数组里的最小的正整数
例如:
给出的数组为[1,2,0] 返回3,
给出的数组为[3,4,-1,1] 返回2.
你需要给出时间复杂度在O(n)之内并且空间复杂度为常数级的算法

Given an unsorted integer array, find the first missing positive integer.
For example,
Given[1,2,0]return3,
and[3,4,-1,1]return2.

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

示例

输入

[1,2,0]

输出

3

解题思路

  • 如果不限制时间复杂度o(n),则可以先排序;如果不限制空间复杂度,则可以用hash
  • 计数排序:利用数组下标来确定元素的正确位置,适用于一定范围内整数排序。
  • 具体到此题,由于缺失的正整数一定是在1~n+1中的(n为数组长度),只需要对1 ~ n范围的数操作,所以满足一定范围内的条件,且满足均为整数的条件,则可利用计数排序的思想。
  • 将所有的正整数放在其对应的数组下标中,如整数5放在A[4]中,然后对数组从前往后遍历,找到第一个不匹配的即为结果。
  • 注:关于正整数 i 放在下标 i - 1 的位置的原因,因为欲调整的整数范围是1~n,而数组下标范围是0 ~n-1,正好可以错位放置。
class Solution {
    
    
public:
    int firstMissingPositive(int* A, int n) {
    
    
        for(int i = 0; i < n; i ++) {
    
    
            //只要当前位置上的数不在正确位置上,就一直交换到正确的数组下标位置
            while(A[i] > 0 && A[i] <= n && A[A[i] - 1] != A[i]) {
    
    
                swap(A[A[i] - 1], A[i]);
            }
        }
        for(int i = 0; i < n; i ++) {
    
    
            //只要出现不匹配,就返回缺失的数
            if(A[i] != i + 1) {
    
    
                return i + 1;
            }
        }
        //如果所有的都匹配
        return n + 1;
    }
};

猜你喜欢

转载自blog.csdn.net/cys975900334/article/details/106583694