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

LeetCode: Merge Sorted Array

一点小失误,基本一次过吧,这段程序不好,参考C#

 1 class Solution {
 2 public:
 3     void merge(int A[], int m, int B[], int n) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         vector<int> C(m);
 7         for (int i = 0; i < m; i++) C[i] = A[i];
 8         int p = 0;
 9         int q = 0;
10         int beg = 0;
11         while (p < m && q < n) {
12             A[beg++] = min(C[p], B[q]);
13             if (C[p] < B[q]) p++;
14             else q++;
15         }
16         if (p == m) {
17             for (int i = q; i < n; i++) A[beg++] = B[i];
18         }
19         if (q == n) {
20             for (int i = p; i < m; i++) A[beg++] = C[i];
21         }
22     }
23 };

 C#

 1 public class Solution {
 2     public void Merge(int[] nums1, int m, int[] nums2, int n) {
 3         for (int i = m+n-1; i >= 0; i--) {
 4             if (m == 0) nums1[i] = nums2[--n];
 5             else if (n == 0) break;
 6             else if (nums1[m-1] < nums2[n-1]) nums1[i] = nums2[--n];
 7             else nums1[i] = nums1[--m];
 8         }
 9     }
10 }
View Code

 

posted @ 2013-04-09 17:35  ying_vincent  阅读(122)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3