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;
        }
    };
  • 相关阅读:
    数据类型及用法
    NFS与SSH
    nginx服务,nginx反向代理
    rpm软件包管理
    磁盘分区,文件系统,软链接和硬链接,内存和进程管理
    Linux常用命令,文件目录和权限管理
    操作系统与网络协议(day3)
    计算机基础之硬件简介(Day2)
    QT写串口
    485传输
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9125042.html
Copyright © 2011-2022 走看看