首页 > 其他 > 详细

LeetCode - First Missing Positive

时间:2014-02-09 16:16:06      阅读:382      评论:0      收藏:0      [点我收藏+]

First Missing Positive

2014.2.8 23:43

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.

Solution1:

  The first solution I thought of was hashing, using unordered_map. This promises O(n) time, but not constant space.

  Solution is simple and runs in one pass. I guess the code can explain itself.

  Time and space complexities are both O(n).

Accepted code:

bubuko.com,布布扣
 1 // 1AC, unordered_map is a good substitute for map
 2 #include <unordered_map>
 3 using namespace std;
 4 
 5 class Solution {
 6 public:
 7     int firstMissingPositive(int A[], int n) {
 8         if (A == nullptr || n <= 0) {
 9             return 1;
10         }
11         
12         unordered_map<int, int> um;
13         int result;
14         int i;
15         
16         result = 1;
17         for (i = 0; i < n; ++i) {
18             if (A[i] > result) {
19                 um[A[i]] = 1;
20             } else if (A[i] < result) {
21                 continue;
22             } else {
23                 um[result] = 1;
24                 ++result;
25                 while (um.find(result) != um.end()) {
26                     ++result;
27                 }
28             }
29         }
30         
31         um.clear();
32         return result;
33     }
34 };
bubuko.com,布布扣

Solution2:

Accepted code:

LeetCode - First Missing Positive

原文:http://www.cnblogs.com/zhuli19901106/p/3541168.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!