[牛客网-Leetcode] #Array is harder first-missing-positive

The first positive integer missing first-missing-positive

Title description

Given an unordered array of integers, find the smallest positive integer that is not in the given array
For example: the
given array is [1,2,0], return 3, and the
given array is [3,4,-1 ,1] returns 2.
You need to give an algorithm whose time complexity is within O(n) and space complexity is constant

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.

Example

enter

[1,2,0]

Output

3

Problem-solving ideas

  • If you do not limit the time complexity o(n), you can sort first; if you do not limit the space complexity, you can use hash
  • Count sort: Use the array subscript to determine the correct position of the element, suitable forWithin a certain rangeofIntegerSort.
  • Specific to this question, because the missing positive integer must be in 1~n+1 (n is the length of the array), you only need to operate on the number in the range of 1~n, so the conditions within a certain range are met, and all of them are satisfied For integer conditions, the idea of ​​counting and sorting can be used.
  • Put all the positive integers in their corresponding array subscripts, such as the integer 5 in A[4], and then traverse the array from front to back, and find the first one that does not match is the result.
  • Note: Regarding the reason why the positive integer i is placed in the position of the subscript i-1, because the range of the integer to be adjusted is 1~n, and the subscript range of the array is 0~n-1, it can be placed in a misplaced position.
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;
    }
};

Guess you like

Origin blog.csdn.net/cys975900334/article/details/106583694