首页 技术 正文
技术 2022年11月14日
0 收藏 679 点赞 2,529 浏览 780 个字

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了,所以,就这样吧。这题简单。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,495
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,297