[LeetCode] First Missing Positive

来源:互联网 发布:淘宝前十名服装店铺 编辑:程序博客网 时间:2024/06/06 09:05

题目

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.

算法应在 O(n) 时间运行,并使用恒定空间。

分析

假设数组为 a ,找正整数, 最好的情况是 a[i] == i + 1 ,如果不满足此条件,数组内又无对应的正整数,就找到了第一个缺失的正整数。

如此一来,主要思路就是在遍历数组是判断每个位置是否有对应的正整数,主要分为以下三种情况。

  1. 满足最好情况——a[i] == i + 1,继续判断数组下一个元素。
  2. 该数不在考虑范围内——如该数为非正数数或大于数组长度,或者该数应放的正确位置已经有的正确的数,此时可以直接扔掉该数,也就是将数组长度减一,把末尾数移到该位置,重新判断数组。
  3. 以上两个条件都不满足,可以将该数它应在的位置上,重新判断数组。

代码

#include <iostream>#include <vector>using namespace std;class Solution {public:    int firstMissingPositive(vector<int>& nums) {        int length = nums.size();        for (int i = 0; i < length;) {            if (nums[i] == i + 1) {                i++;            } else if ((nums[i] <= i) || (nums[i] > length) || (nums[nums[i] - 1] == nums[i])) {                nums[i] = nums[--length];            } else {                swap(nums[i], nums[nums[i] - 1]);            }        }         return length + 1;    }};int main() {    int num[] = {3, 4, -1, 1};    int length = sizeof(num) / sizeof(int);    vector<int> nums(num, num + length);    Solution solution;    int number = solution.firstMissingPositive(nums);    cout << "The first missing positive integer is " << number << endl;}
原创粉丝点击