码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode笔记:First Missing Positive

时间:2015-12-24 07:05:55      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

一. 题目描述

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, 2, 0],由于第一个未出现的正整数是3,则返回3[3, 4, -1, 1]第一个未出现的正整数是2,则返回2。算法要求在O(n)的时间复杂度及常数空间复杂度内完成。

一种方法是,先把数组里每个正整数从i位放到第i-1位上,这样就形成了有序的序列,然后检查每一下标index与当前元素值,就能知道当前下标所对应的正整数是否缺失,若缺失则返回下标index + 1即可。

三. 示例代码

#include <iostream>
#include <vector>

using namespace std;

class Solution
{
public:
    int firstMissingPositive(vector<int>& nums)
    {
        int n = nums.size();
        for (int i = 0; i < n; ++i)
        {
            int temp = 0;
            while (i + 1 != nums[i] && nums[i] != nums[nums[i] - 1] && nums[i] > 0)
            {
                temp = nums[i];
                nums[i] = nums[temp - 1];
                nums[temp - 1] = temp;
            }
        }

        for (int i = 0; i < n; ++i)
        {
            if (i + 1 != nums[i])
                return i + 1;
        }

        return n + 1;
    }
};

leetcode笔记:First Missing Positive

标签:

原文地址:http://blog.csdn.net/liyuefeilong/article/details/50391668

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!