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

    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开始的正整数,第一个没有在所给数组中出现的正整数。

    因为是从1开始的,我们可以将数组中所有的正整数都移动到它的正确位置,当所有数字都移动完毕后,从头检查第一个没有出现在该出现位置上的正整数就是所求的数字。若所有的数都出现了,则所求的数字就是n + 1,所有数字后面的那个数字。

    该算法因为所有数字都是移动到自己的正确位置,因此每个数字都只会被移动一次。复杂度因此是O(n)。

    所给数组中如果出现了重复的数字也不要紧,因为随着交换,所有正整数都回到了自己的正确位置后,重复数字会被交换到剩余的位置中去。而这些位置并不是他们的正确位置,因此也能指示出他们所处位置的正数缺失了。

     1 class Solution {
     2 public:
     3     int firstMissingPositive(vector<int>& nums) {
     4         int n = nums.size();
     5         for (int i = 0; i < n; i++)
     6             while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i])
     7                 swap(nums[i], nums[nums[i] - 1]);
     8         for (int i = 0; i < n; i++)
     9             if (nums[i] != i + 1)
    10                 return i + 1;
    11         return n + 1;
    12     }
    13 };
  • 相关阅读:
    OD: Memory Attach Technology
    Chrome: Shockwave Flash isn't responding
    OD: Memory Attach Technology
    OD: Heap Exploit : DWORD Shooting & Opcode Injecting
    OD: Heap in Windows 2K & XP SP1
    OD: Writing Small Shellcode
    OD: Shellcode Encoding
    Set Windows IP by Batch
    OD: Universal Shellcode
    XenServer 使用笔记
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5171025.html
Copyright © 2011-2022 走看看