41. First Missing Positive

来源:互联网 发布:国债收益率 知乎 编辑:程序博客网 时间:2024/05/17 06:03

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),空间复杂度为O(1)。所以不能排序,不能新建一个数组记录某个数是否出现,只能对原数组做操作,如果nums[i]大于0且小于等于nums数组的大小(即此值减1能作为索引),则将nums[i]与nums[nums[i]-1]交换(如果这两个值一样就不用管了)。这样就能使数组索引为i处的值为i+1(前提是i+1在原数组中存在)。这样再遍历一次数组,如果某处i的值不为i+1,说明缺失这个值,直接返回i+1,如果遍历完都没有返回,则返回n+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;    }};


0 0
原创粉丝点击