【leetcode】41. First Missing Positive 求不在给定数组里的最小的正整数

1. 题目

Given an unsorted integer array, find the first missing positive integer.spa

For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.code

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

2. 思路

遍历找到全部的正数,并创建hashmap。
同时记录下遍历过程当中找到的第一个未验证的最小不存在正数起点。
而后从这个点开始每次递增1的在hashmap中验证是否存在。最多只会验证“正数的个数”次。
即复杂度O(N)it

3. 代码

耗时:6msio

class Solution {
public:
    // 1. 第一遍找到正数的最小值的某一个局部最优起始位, 同时创建hashmap
    // 2. 从最小值开始递增1的查找是否存在,最多只会查找“整数的个数个”
    int firstMissingPositive(vector<int>& nums) {
        unordered_set<int> set;
        int start = 1;
        //int count = 0;
        for (int i = 0; i < nums.size(); i++) {
            int iv = nums[i];
            if (iv <= 0) continue;
            //++count;
            set.insert(iv);
            if (iv == start) {
                start++;
            }
        }
        while (true) {
            if (set.find(start) != set.end()) {
                ++start;
                continue;;
            } else {
                break;
            }
        }
        return start;
    }
};
相关文章
相关标签/搜索