LeetCode First Missing Positive
发布时间:2020-12-13 20:15:15 所属栏目:PHP教程 来源:网络整理
导读:Given an unsorted integer array,find the first missing positive integer. For example, Given [1,2,0] return 3 , and [3,4,⑴,1] return 2 . Your algorithm should run in O ( n ) time and uses constant space. 题意:找到第1个最小的正整数。 思路
Given an unsorted integer array,find the first missing positive integer.
For example, Your algorithm should run in O(n) time and uses constant space. 题意:找到第1个最小的正整数。思路:由于要求不能用到额外的空间,题目有暗示:答案在[1,n+1]之间。每一个位置都试着将这个位置的值换到对应的下标,这样第1个位置出现不是相应的值的时候就是答案,还有就是要是都能对应,那末n+1就是解 class Solution {
public:
int firstMissingPositive(int A[],int n) {
for (int i = 0; i < n; i++) A[i]--;
for (int i = 0; i < n; i++) {
while (A[i] != i && A[i] >= 0 && A[i] < n) {
if (A[i] == A[A[i]]) break;
swap(A[i],A[A[i]]);
}
}
for (int i = 0; i < n; i++)
if (A[i] != i)
return i + 1;
return n+1;
}
};
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |