[Problem] The missing first positive number

Question requirements
Give you an unsorted integer array. Please find the smallest positive integer that does not appear in it.

示例 1:
输入: [1,2,0]
输出: 3
示例 2:
输入: [3,4,-1,1]
输出: 2
示例 3:
输入: [7,8,9,11,12]
输出: 1

Problem-solving ideas
1. First replace all abnormal numbers in the array (negative numbers, zeros or numbers greater than the number of the array) with 1
2. By changing the number on the subscript pointed to by each number into a negative number, finally traverse Find the first positive number in the array. If there is no positive number in the entire array, take the last digit of the number of the array.
3. In special cases, because there will be multiple repeated numbers in the array, we need to take the absolute value of the target object before turning it negative.


Lizou Compiler

int firstMissingPositive(int* nums, int numsSize){
    
    
//1、我们先遍历一遍数组,判断是否有1,有则将负数、零和大于数组个数的数替换成1,否则直接返回1
    int count = 0;
    for(int i = 0; i < numsSize; ++i){
    
    
        if(nums[i] == 1)
            count++;
    }
    if(!count++)
        return 1;

    for(int i = 0 ; i < numsSize; ++i){
    
    
        if(nums[i] <= 0 || nums[i] > numsSize)
            nums[i] = 1;
    }
//2、继续遍历数组,将每个元素的数字指向下标上的元素变成负数
//特殊情况,因为数组中会有多个重复数字,所以我们要把下标的元素取绝对值再取负
    for(int i = 0; i < numsSize; ++i){
    
    
        int index = abs(nums[i]);
        nums[index - 1] = - abs(nums[index - 1]);
    }

//3、遍历数组,将遇到的第一个正整数的下标 + 1输出
    for(int i = 0; i < numsSize; ++i){
    
    
        if(nums[i] > 0)
            return i + 1;
    }

    return numsSize + 1;
}

Update progress this month 7/15

Creation is not easy, your likes are my biggest motivation! ! !
See you next time end~

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43776724/article/details/107012834