zoukankan      html  css  js  c++  java
  • First Missing Positive

    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.

     Analyse: 

    1. sort and locate the positive first number.

      Runtime: 4ms.

     1 class Solution {
     2 public:
     3     int firstMissingPositive(vector<int>& nums) {
     4         sort(nums.begin(), nums.end());
     5         
     6         int positive = 1;
     7         for(int i = 0; i < nums.size(); i++){
     8             if(nums[i] > 0){
     9                 if(nums[i] != positive) return positive;
    10                 for(int j = i; j < nums.size() - 1; j++){
    11                     if(nums[j + 1] - nums[j] <= 1) continue;
    12                     return nums[j] + 1;
    13                 }
    14                 return nums[nums.size() - 1] + 1;
    15             } 
    16         }
    17         return positive;
    18     }
    19 };

    2. put nums[i] at (i + 1)-th index. For each element satisfying this requirement, we put it in the right position. For those not, if they are large than the vector's size or are negative numbers or equals to nums[nums[i] - 1], we can ignore this element and deal with the next element. 

      Runtime: 4ms.

     1 class Solution {
     2 public:
     3     int firstMissingPositive(vector<int>& nums) {
     4         int n = nums.size();
     5         
     6         for(int i = 0; i < n; i++){
     7             while(nums[i] != i + 1){
     8                 if(nums[i] < 0 || nums[i] > n || nums[i] == nums[nums[i] - 1]) break;
     9                 swap(nums[i], nums[nums[i] - 1]);
    10             }
    11         }
    12         
    13         for(int j = 0; j < n; j++){
    14             if(nums[j] != j + 1) return j + 1;
    15         }
    16         return n + 1;
    17     }
    18 };
  • 相关阅读:
    3. 尾缀
    Cocos工程命名规则整理(node部分)
    3.1-3.3 HBase Shell创建表
    2.11-2.12 HBase的数据迁移常见方式
    2.8-2.10 HBase集成MapReduce
    2.7 HBase架构深入剖析
    2.3-2.6 HBase java API
    2.1-2.2 HBase数据存储
    1.6-1.8 HBase表的物理模型
    1.4-1.5 HBase部署及基本使用
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4699228.html
Copyright © 2011-2022 走看看