【LeetCode算法练习(C++)】First Missing Positive
来源:互联网 发布:java object 类型转换 编辑:程序博客网 时间:2024/06/06 04:44
题目:
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.
链接:First Missing Positive
解法:打表,将出现的正数在表中置0,遍历列表返回第一个非0的序号。时间O(n)
class Solution {public: int firstMissingPositive(vector<int>& nums) { vector<int> tmp; int len = nums.size(); if (len == 0) return 1; for (int i = 0; i <= len; i++) { tmp.push_back(i); } for (int i = 0; i < len; i++) { if (nums[i] > 0 && nums[i] <= len) tmp[nums[i]] = 0; } for (int i = 0; i <= len; i++) { if (tmp[i]) return i; } return len + 1; }};
Runtime: 3 ms
阅读全文