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

    Subscribe to see which companies asked this question.

    刚开始想用unordered_map, 后来发现要求常数空间,这种办法自然行不通了。

    看了网上的解法,用到了桶排序,一下子豁然开朗。之前知道桶排序的原理,总感觉很蠢。现在发现,所有算法之所以存在,就有它存在到道理。

    参考题解如下:http://www.acmerblog.com/leetcode-solution-first-missing-positive-6304.html

    关于桶排序,网上有很多讲解,这里不介绍。 对于所给数组,运用桶排序,可以将所有数组中的值放入它的对应位置,即arr[i] = i。然后从前往后找第一个arr[i] != i 即为所求。

    class Solution {
    public:
        int firstMissingPositive(vector<int>& nums) {
            
            int n = nums.size();
            for(int i=0; i<n; ++ i)
            {
                while(nums[i] != i+1)
                {
                    if(nums[i] <= 0 || nums[i] > n || nums[i] == nums[nums[i] - 1])
                        break;
                    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;
        }
    };
    
  • 相关阅读:
    前端模块化开发的价值
    Promise对象
    avalon define新老风格对比
    jQuery知识点1
    SASS
    HTML5
    JSON
    css垂直居中
    maven nexus 部署
    Linux 平台下 lzo和hadoop-lzo安装与集成
  • 原文地址:https://www.cnblogs.com/aiterator/p/6628812.html
Copyright © 2011-2022 走看看