zoukankan      html  css  js  c++  java
  • LeetCode: first Missing Positive

    Title:

    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.

    思路:将元素放到合适的位置,例如1放到数组中0的位置,2放到1的位置...

    class Solution {
    public:
        int firstMissingPositive(vector<int>& nums) {
            int n = nums.size();
            for (int i = 0; i < n; ++i) {
                while (nums[i] > 0 && nums[i] <= n && 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;
        }
    };
    

      

  • 相关阅读:
    书_Delphi
    20160226
    SVG_style_script
    辅助
    电影_Z
    Windows下软件调试
    20160221
    Qt5.3.2_vs10_发布时所需DLL的路径
    android intent 传数据
    android 消息机制
  • 原文地址:https://www.cnblogs.com/yxzfscg/p/4449661.html
Copyright © 2011-2022 走看看