LeetCode: First Missing Positive
2013-03-21 11:02
447 查看
一开始有失误,发现如果外面定义了int ret, for循环里第一个条件为int ret = 1的话,这里的ret跟外面的ret不一样。少数次过
上面代码有错,题目要求是constant memory,下面这段代码是正确的
C#:没有swap函数,注意swap的顺序
View Code
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
相关文章推荐
- LeetCode-First Missing Positive
- LeetCode 41:First Missing Positive Number
- leetcode: First Missing Positive
- leetcode -- First Missing Positive -- 简单trick题目
- First Missing Positive - Java Leetcode
- 【leetcode】First Missing Positive
- LeetCode_FirstMissingPositive
- LeetCode() First Missing Positive
- [LeetCode][Java] First Missing Positive
- [leetcode]First Missing Positive
- First Missing Positive -- LeetCode
- leetcode习题解答:First Missing Positive
- leetcode -- First Missing Positive
- [LeetCode(Q41)] First Missing Positive (乱序数组中寻找第一个未出现的正整数)
- [LeetCode] First Missing Positive (Hasing)
- [Leetcode] First Missing Positive
- [LeetCode]First Missing Positive
- LeetCode----First Missing Positive
- Leetcode: First Missing Positive
- 【Leetcode】First Missing Positive