leetcode题目例题解析(十二)

leetcode题目例题解析(十二)

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. >For example,

题意解析:

这道题目就是要寻找一个给定数组中未出现的第一个正数,这道题也是今年(2017)考研计算机综合408的数据结构算法题。

解题思路:

由于这道题只处理正数,所以与负数无关,不用管
我们可以发现,数组的容量为n,那么最多可以容纳n个正数,要找到未出现的最小的正数,我们可以让每个小于n的正数放到数组的n-1的位置,那么最终数组中按顺序的第一个不符合这个规则的位置,对应+1就是未出现的最小正数。

代码:

class Solution {
public:
    void swap(int& a, int& b) {//交换两个数
        a ^= b;
        b ^= a;
        a ^= b;
    }
    int firstMissingPositive(vector<int>& nums) {
        int s = nums.size();
        int ans = s + 1;//对于一个完全按顺序出现的正数组,默认其结果为s+1
        for (int i = 0; i < s; i++) {
            while (nums[i] > 0&&nums[i] != nums[nums[i] - 1]&&nums[i] <= s) {
                swap(nums[i], nums[nums[i] - 1]);
            }
        }
        for (int i = 0; i < s; i++) {
            if (nums[i] != i + 1) {//第一个不满足条件的位置
                ans = i + 1;
                break;
            }
        }
        return ans;
    }
}; 

原题目链接:
https://leetcode.com/problems/first-missing-positive/description/

猜你喜欢

转载自blog.csdn.net/OzhangsenO/article/details/78925425