LeetCode: First Missing Positive
一开始有失误,发现如果外面定义了int ret, for循环里第一个条件为int ret = 1的话,这里的ret跟外面的ret不一样。少数次过
1 class Solution { 2 public: 3 int firstMissingPositive(int A[], int n) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 map<int, int> s; 7 int maxs = 0; 8 for (int i = 0; i < n; i++) { 9 maxs = max(maxs, A[i]); 10 s[A[i]] = 1; 11 } 12 int ret = 1; 13 for (ret = 1; ret <= maxs; ret++) { 14 if (s.count(ret) == 0) break; 15 } 16 return ret; 17 } 18 };
上面代码有错,题目要求是constant memory,下面这段代码是正确的
1 class Solution { 2 public: 3 int firstMissingPositive(int A[], int n) { 4 // IMPORTANT: Please reset any member data you declared, as 5 // the same Solution instance will be reused for each test case. 6 for (int i = 0; i < n; i++) 7 if (A[i] != i+1) 8 while (A[i] > 0 && A[i] < n && A[A[i]-1] != A[i]) swap(A[i], A[A[i]-1]); 9 for (int i = 0; i < n; i++) 10 if (A[i] != i+1) return i+1; 11 return n+1; 12 } 13 };
C#:没有swap函数,注意swap的顺序
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public int FirstMissingPositive(int[] nums) { 3 for (int i = 0; i < nums.Length; i++) { 4 if (nums[i] != i + 1) { 5 while (nums[i] > 0 && nums[i] < nums.Length && nums[nums[i] - 1] != nums[i]) { 6 int tmp = nums[nums[i] - 1]; 7 nums[nums[i] - 1] = nums[i]; 8 nums[i] = tmp; 9 } 10 } 11 } 12 for (int i = 0; i < nums.Length; i++) 13 if (nums[i] != i + 1) return i + 1; 14 return nums.Length + 1; 15 } 16 }