您的位置:首页 > 其它

LeetCode: First Missing Positive

2013-03-21 11:02 447 查看
一开始有失误,发现如果外面定义了int ret, for循环里第一个条件为int ret = 1的话,这里的ret跟外面的ret不一样。少数次过

class Solution {
public:
int firstMissingPositive(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
map<int, int> s;
int maxs = 0;
for (int i = 0; i < n; i++) {
maxs = max(maxs, A[i]);
s[A[i]] = 1;
}
int ret = 1;
for (ret = 1; ret <= maxs; ret++) {
if (s.count(ret) == 0)  break;
}
return ret;
}
};


上面代码有错,题目要求是constant memory,下面这段代码是正确的

class Solution {
public:
int firstMissingPositive(int A[], int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
for (int i = 0; i < n; i++)
if (A[i] != i+1)
while (A[i] > 0 && A[i] < n && A[A[i]-1] != A[i]) swap(A[i], A[A[i]-1]);
for (int i = 0; i < n; i++)
if (A[i] != i+1) return i+1;
return n+1;
}
};


C#:没有swap函数,注意swap的顺序

public class Solution {
public int FirstMissingPositive(int[] nums) {
for (int i = 0; i < nums.Length; i++) {
if (nums[i] != i + 1) {
while (nums[i] > 0 && nums[i] < nums.Length && nums[nums[i] - 1] != nums[i]) {
int tmp = nums[nums[i] - 1];
nums[nums[i] - 1] = nums[i];
nums[i] = tmp;
}
}
}
for (int i = 0; i < nums.Length; i++)
if (nums[i] != i + 1) return i + 1;
return nums.Length + 1;
}
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: