LeetCode-41-First Missing Positi

2020-01-21  本文已影响0人  突击手平头哥

LeetCode-41-First Missing Positive

题目

Given an unsorted integer array, find the smallest missing positive integer.

Example 1:

Input: [1,2,0]
Output: 3
Example 2:

Input: [3,4,-1,1]
Output: 2
Example 3:

Input: [7,8,9,11,12]
Output: 1

Note:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-missing-positive
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目分析

C++实现

class Solution {
public:
    int firstMissingPositive(vector<int>& nums) {
        int n = nums.size();

        bool contain1 = false;
        for(int i = 0; i < n; i++)
            if(nums[i] == 1)
                contain1 = true;
            else if(nums[i] <= 0 || nums[i] > n)
                nums[i] = 1;
            //因为需要用正负数来表示是否存在, 并且负数、0、大于n的值都不需要考虑, 所以设置为1

        if(!contain1) return 1;         //不包含1, 那么结果就是1
        if(n == 1)  return 2;           //如果长度仅为1, 并且包含了数1, 那么结果是2

        for(int i = 0; i < n; i++)
        {
            int t = abs(nums[i]);
            if(t == n)
                nums[0] = -1 * abs(nums[0]);             //负数表示存在
            else
                nums[t] = -1 * abs(nums[t]);
        }

        for(int i = 1; i < n; i++)
            if(nums[i] > 0)
                return i;
        if(nums[0] > 0) return n;
        return n+1;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读