• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ying_vincent
博客园    首页    新随笔    联系   管理    订阅  订阅

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的顺序

 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 }
View Code

 

posted @ 2013-03-21 11:02  ying_vincent  阅读(152)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3