[41] leetcode Lack of a positive number (the array, a hash map)

Topic links: https://leetcode-cn.com/problems/first-missing-positive/

Title Description

Given an unsorted array of integers, find the smallest positive integer which does not arise.

Example 1:

输入: [1,2,0]
输出: 3

Example 2:

输入: [3,4,-1,1]
输出: 2

Example 3:

输入: [7,8,9,11,12]
输出: 1

Description:

Your time complexity of the algorithm should be O (n), and can only use a constant level space.

Thinking

First, we determine a fact: the first positive number in the missing must be (1, n) between;
we consider the method hash table mapping:

  • Assuming that the original array is A. Tmp first construct a temporary array, is initialized to 0, a size of a.size (). Traverse A, the A [i] to copy tmp [A [i] -1] position. If A [i] - 1 exceeds the range of tmp, directly thrown away. Thus, tmp [0 ... size) is saved in the value of a portion of the A. Then start checking tmp from position 0, if it is found that the value of the location and index numbers do not match, it means to find the missing number.

Note that the above program needs additional space, we consider in-place algorithm, operating directly in the original array, put each number in the correct position. Using seat exchange :

(1) starting with the first position, if nums[i] > 0 && nums[i] <= nums.size(), are constantly exchange num[i]and nums[nums[i] -1], until nums[nums[i]] - 1] = i
(2) to the second position to the n-th position Do the same

Complexity Analysis

  • Time complexity: O (n). Analyzing a maximum of 2n in the process of switching, up traversal verification process n times, a total of up to 3n times.
  • Space complexity: O (1)

Code

class Solution {
public:
    int firstMissingPositive(vector<int>& nums) {

        // 把num[i]放到nums[i]-1的位置上;最多循环内最多2n次
        for (int i = 0; i < nums.size(); ++i) {
            // 最后的条件保证不重复交换
            while (nums[i] > 0 && nums[i] <= nums.size() && nums[i] != nums[nums[i]-1])
                swap(nums[i], nums[nums[i] -1]);
        }
        for (int i = 0; i < nums.size(); ++i) {
            if(nums[i]!=i+1)
                return i+1;
        }
        return nums.size()+1;
    }
};

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/zjwreal/article/details/94553485