首页 > 代码库 > LeetCode ---- Merge Sorted Array
LeetCode ---- Merge Sorted Array
题目链接
Problem discription
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 (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
Accpted Code 1 ( use extra space)
1 class Solution {
2 public:
3 void merge(int A[], int m, int B[], int n) {
4 // we use "ai" and "bi" to keep trace
5 // of array A[] and B[] respectively
6 // "ci" holds the number of elements that
7 // has been merged
8 int ai = 0, bi = 0, ci = 0;
9 // create an extra vector of size n+m
10 // to keep the sorted array
11 vector<int> C(n + m);
12 while (ci < n + m) {
13 // from small to large
14 if (ai < m && (bi >= n || A[ai] <= B[bi])) {
15 C[ci++] = A[ai++];
16 } else {
17 C[ci++] = B[bi++];
18 }
19 }
20 // copy the sorted array from C to A
21 for (int i = 0; i < n+m; i++) A[i] = C[i];
22 }
23 };
Accepted Code (without extra space) Clear & Simple
1 class Solution {
2 public:
3 void merge(int A[], int m, int B[], int n) {
4 // we use "ai", "bi" to iterator A[] and B[]
5 // from the end respectively
6 // since the size of A[] equal to or greater n+m
7 // thus we can use inplace sort by filling A[]
8 // from A[n+m-1] to A[0]
9 int ai = m - 1, bi = n - 1, ci = n + m - 1;
10 while (ci >= 0) {
11 if (ai >= 0 && (bi < 0 || A[ai] >= B[bi])) {
12 A[ci--] = A[ai--];
13 } else {
14 A[ci--] = B[bi--];
15 }
16 }
17 }
18 };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。