您的位置:首页 > 其它

【LeetCode练习题】Merge Sorted Array

2014-04-07 23:37 344 查看


Merge Sorted Array

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 andn respectively.



题目意思:

将两个有序的数组合并成一个有序的数组。A和B合并到A中且A中的空间足够。

解题思路:

1,逗比的解法。

int compare(const void *p1,const void *p2){
int a = *(int *)p1;
int b = *(int *)p2;
return a-b;
}
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
for(int i = m,j = 0; i < m+n; i++,j++){
A[i] = B[j];
}
qsort(A,m+n,sizeof(int),compare);
}
};


2,题目想要我们这样解。

跟合并两个链表是差不多的。区别在两个数组A和B从后往前来一一的作比较,而链表是从头开始比较的。

class Solution {
public:
void merge(int A[], int m, int B[], int n) {
int pa = m - 1, pb = n - 1, pr = m + n - 1;
while(pa >= 0 && pb >= 0) {
if(A[pa] > B[pb])
A[pr--] = A[pa--];
else
A[pr--] = B[pb--];
}
while(pb >= 0)
A[pr--] = B[pb--];
}
};


╭(╯^╰)╮……Anyway

反正两种方法都AC了,所以,就这样吧。这题简单。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: