博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 88 Merge Sorted Array
阅读量:6900 次
发布时间:2019-06-27

本文共 1583 字,大约阅读时间需要 5 分钟。

Problem:

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

Summary:

将已排序数组nums1和nums2 merge进nums1中,其中nums1和nums2的初始化元素数目分别为m和n。

默认nums1的空间大于m+n。

Solution:

1. 由于nums1有m个元素,nums2有n个元素,最终数组有m + n个元素。

我们从第m + n - 1个元素开始向前排列新数组,我所理解的原因为:

若从前往后排列数组,需要多次整体后移nums1数组中原有元素的位置,时间复杂度过低。而从后往前排列,可以在保证保留nums1未排列数组位置的情况下降低时间复杂度。

1 class Solution { 2 public: 3     void merge(vector
& nums1, int m, vector
& nums2, int n) { 4 int i = m - 1, j = n - 1; 5 int next = m + n - 1; 6 while (j >= 0) { 7 nums1[next--] = i >= 0 && nums1[i] > nums2[j] ? nums1[i--] : nums2[j--]; 8 } 9 }10 };

2. 首先将nums2的所有元素接在nums1后面,再用冒泡排序法对整个数组进行排序。

1 class Solution { 2 public: 3     void merge(vector
& nums1, int m, vector
& nums2, int n) { 4 for (int i = 0; i < n; i++) { 5 nums1[m + i] = nums2[i]; 6 } 7 8 int len = m + n; 9 for (int i = 0; i < len - 1; i++) {10 for (int j = i + 1; j < len; j++) {11 if (nums1[i] > nums1[j]) {12 int tmp = nums1[i];13 nums1[i] = nums1[j];14 nums1[j] = tmp;15 }16 }17 }18 }19 };

 

转载于:https://www.cnblogs.com/VickyWang/p/6239163.html

你可能感兴趣的文章
vscode开发c#
查看>>
Html5移动端页面自适应布局详解(rem布局)
查看>>
collections模块
查看>>
2018-2019-1 20165302 《信息安全系统设计基础》第六周学习总结
查看>>
黑马程序员--浅谈进程与线程
查看>>
ROS-十步完成ROS-indigo安装
查看>>
WinDbg双机调试配置
查看>>
.net断点续传的原理
查看>>
仿微博php生成短网址
查看>>
前端开发必备站点汇总
查看>>
SQL语句熟悉
查看>>
Android:多语言对应实现
查看>>
计蒜客 宝藏 (状压DP)
查看>>
开个小灶——turtle 海龟图形
查看>>
C++11 auto and decltype
查看>>
微信小程序 页面跳转navigator与传递参数
查看>>
常用正则表达式速查表
查看>>
Lua模式匹配
查看>>
poj 1251
查看>>
spring_3最小化Spring XML配置
查看>>