您的位置:首页 > 编程语言 > C#

LeetCode Online Judge 题目C# 练习 - Merge Sorted Array

2012-09-28 05:04 686 查看
Given two sorted integer arrays A and B, merge B into A as one sorted array.

Note:
You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.

public static void MergeSortedArray(int[] A, int m, int[] B, int n)
{
if (m == 0)
{
A = B;
return;
}
if (n == 0)
return;

//move all the element in A[] to the end
for (int i = 0; i < m; i++)
{
A[i + m] = A[i];
}

//Merge
int p = m, q = 0, k = 0;
while (p < A.Length || q < B.Length)
{
if (p == A.Length)
{
A[k++] = B[q++];
continue;
}
if (q == B.Length)
{
A[k++] = A[p++];
continue;
}

if (A[p] <= B[q])
{
A[k++] = A[p++];
continue;
}
else
{
A[k++] = B[q++];
continue;
}
}
}


代码分析:

  O(n), 就是把A[]的数字全部移到尾部,再跟B[] merge。应该也可以直接从后往前merge,大的先走!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: