您的位置:首页 > 其它

#189 First Missing Positive

2016-08-21 08:23 239 查看
题目描述:

Given an unsorted integer array, find the first missing positive integer.

Have you met this question in a real interview? 

Yes

Example

Given 
[1,2,0]
 return 
3
,

and 
[3,4,-1,1]
 return 
2
.

Challenge 

Your algorithm should run in O(n) time and uses constant space.

题目思路:

这题找第一个缺少的positive number,想到可以把array中的index利用起来:我们可以规定,index 0必须放1,index 1必须放2,etc。这样在第一次遍历数组时,我们把数字都尽量挪到规定的位置中去(有些太大或者小于等于0的数字不能挪的,就算了)。然后第二次遍历数组时,如果遇到数字不在规定的位置,它的index + 1就是我们所求的答案。

这里需要注意重复数字的情况,我们在第一次遍历和swap时,需要对这个情况设定break条件,以免dead lock。

Mycode(AC = 24ms):

class Solution {
public:
/**
* @param A: a vector of integers
* @return: an integer
*/
int firstMissingPositive(vector<int> A) {
// write your code here
for (int i = 0; i < A.size(); i++) {
// swap the number to the correct position
while (A[i] != i + 1 && A[i] - 1 >= 0 && A[i] - 1 < A.size()) {
swap(A, A[i] - 1, i);
// to avoid dead lock
if (A[i] == A[A[i] - 1]) break;
}
}

// if the number is not at correct position,
// then it indicates the first missing pos
for (int i = 0; i < A.size(); i++) {
if (A[i] != i + 1) {
return i + 1;
}
}

return A.size() + 1;
}

void swap(vector<int>& A, int i, int j) {
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lintcode array