zoukankan      html  css  js  c++  java
  • 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.

    解题思路:

    这道题如果不要求空间复杂度为O(1)的话,我们可以使用hashmap来存储已经出现的数字及其个数,遍历一遍数组存入hashmap并算取最大值。

    第二遍遍历1到最大值,第一个无法在map中找到的即为返回值,否则返回最大值加1.

    可是这道题要求了空间复杂度为O(1)!!!

    那就说明我们可能要改动数组。

    排序?不符合空间复杂度的要求

    这里用了一个很巧妙的方法:将数字n放到n-1的位置上去。

    从头遍历数组时,若nums[i] != i+1则说明该数字缺失。

    代码:

    class Solution {
    public:
        int firstMissingPositive(vector<int>& nums) {
            int n = nums.size();
            for(int i = 0; i < n; i++){
                while(nums[i] <= n && nums[i] > 0 && nums[nums[i] - 1] != nums[i]){
                    swap(nums[i], nums[nums[i] - 1]);
                }
            }
            for(int i = 0; i < n; i++){
                if(nums[i] != i+1)
                    return i+1;
            }
            return n+1;
        }
    };
  • 相关阅读:
    统计SQL
    记一次惨痛教训
    window ssh 连接 本地虚拟机ubuntu 16
    js undefined 笔记
    java new java.text.SimpleDateFormat("yyyyMM01").format(date)
    java 反射
    mapinfo使用
    EnableAutoConfiguration注解说明
    Eureka Server 代码分析01
    BigDecimal 学习比较
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9125042.html
Copyright © 2011-2022 走看看