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

leetcode .First Missing Positive

时间:2014-11-13 22:11:38      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   ar   os   sp   for   div   on   

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.

对于元素为n的数组A, 正数个数 <= n, 那么第一个miss的正数必然 <= n+1。这样,可以把负数置成n+2,不影响结果。

假设数字k 属于 [1, n],且在数组A中的j位置出现,即A[j] = k。把数组A中所有的k置成-k, 那么留下第一个正数的位置j

即为第一个miss的正数。

 1     int firstMissingPositive(int A[], int n) 
 2     {
 3         int i = 0, temp = 0, inf = n + 2;
 4         
 5         for (i = 0; i < n; i++)
 6             A[i] = (A[i] <= 0) ? inf : A[i];
 7             
 8         for (i = 0; i < n; i++)
 9         {
10             temp = A[i] > 0 ? A[i] : -A[i];
11             if (temp > n)
12                 continue;
13             if (A[temp - 1] > 0) /* in case that A has duplicate value and A[temp - 1] will * -1 twice. */ 
14                 A[temp - 1] *= -1;
15         }
16         
17         for (i = 0; i < n; i++)
18         {
19             if (A[i] > 0)
20                 return i + 1;
21         }
22         
23         return i + 1;
24     }

 

leetcode .First Missing Positive

标签:style   blog   color   ar   os   sp   for   div   on   

原文地址:http://www.cnblogs.com/ym65536/p/4095897.html

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