zoukankan      html  css  js  c++  java
  • LeetCode OJ:First Missing Positive (第一个丢失的正数)

    在leetCode上做的第一个难度是hard的题,题目如下:

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

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

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

    关键是要实现0(N)的时间复杂度以及常数级别的空间复杂度,先贴上我写的函数,完全不能达到上面的要求,只能实现NlgN的时间复杂度:

     1 class Solution {
     2 public:
     3     int firstMissingPositive(vector<int>& nums) {
     4         sort(nums.begin(), nums.end());
     5         int sz = nums.size();
     6         if(sz == 0) return 1;
     7         int index;
     8         for (index = 0; index < sz; index++){
     9             if (nums[index] <= 0)
    10                 continue;
    11             else
    12                 break;
    13         }
    14         if (nums[index] != 1 || index == sz) return 1;  //当没有正数的情况或正数的第一个数不是1的情况
    15         while (index < sz){
    16             if (nums[index + 1] != nums[index] && nums[index + 1] != nums[index] + 1) //两个判断主要是为了防止vector中重复的数字出现。
    17                 return nums[index] + 1;
    18             index++;
    19         }
    20         return nums[index] + 1;
    21     }
    22 };

    由于达不到时间以及空间复杂度的要求,实在想不出来,我去看了下别人写的,现在由于vector可能会出现重复的数,我暂时不知带怎样去解决,只有先这样,回头有时间再回来填坑。

  • 相关阅读:
    洛谷P5281 [ZJOI2019] Minimax搜索
    势函数
    Comet OJ [Contest #5] 迫真大游戏
    洛谷P3307 [SDOI2013] 项链
    洛谷P5985 [PA2019] Muzyka pop
    CF1205E Expected Value Again
    review
    CF891E Lust
    线性代数
    洛谷P4607 [SDOI2018] 反回文串
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4868511.html
Copyright © 2011-2022 走看看