【LeetCode练习题】Merge Sorted Array

时间:2024-07-09 22:05:50

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 = ; 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 - , pb = n - , pr = m + n - ;
while(pa >= && pb >= ) {
if(A[pa] > B[pb])
A[pr--] = A[pa--];
else
A[pr--] = B[pb--];
}
while(pb >= )
A[pr--] = B[pb--];
}
};

╭(╯^╰)╮……Anyway

反正两种方法都AC了,所以,就这样吧。这题简单。