LeetCode 41.First Missing Positive (缺失的第一个正数)

题目描述:

给定一个未排序的整数数组,找出其中没有出现的最小的正整数。\

示例:

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

Accepted C++ Solution:

class Solution {
public:
    int firstMissingPositive(vector<int>& nums) {
        if(nums.empty())
            return 1;
        
        sort(nums.begin(),nums.end());
        int n = nums.size();
        int i = 0;
        while(nums[i] <= 0 && i < n)
            i++;
        
        int cnt = 1;
        
        while(nums[i] == cnt) {
            if(nums[i] == nums[i+1]) {    //跳过重复的元素
                i++;
                continue;
            }
            i++;
            cnt++;
        }
        
        return cnt;
    }
};

先进行排序,过滤掉负数。

从1开始一一对应。

猜你喜欢

转载自blog.csdn.net/amoscykl/article/details/82779548