当前位置: 首页 > news >正文

LeetCode 88 - Merge Sorted Array 合并有序数组

题目

You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.

Merge nums1 and nums2 into a single array sorted in non-decreasing order.

The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.

思路

数字交换是这道题要解决的问题。如果从前往后进行排序,那么nums1每插入一个数字,后面的数字都要依序往后移动,时间复杂度高达(1 - n) * n / 2. 因此考虑从后往前排序,nums1后面正好有空位可以执行。
时间复杂度 在无需创建新的空间之下(空间复杂度为O(1)),如果nums2所有数字均比nums1最大值大,那么时间复杂度为O(n);如果nums2数字和nums1数字大小交替,那么时间复杂度为O(m + n)

C++代码

class Solution {
public:void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {int i = m - 1, j = n - 1, p = m + n;while(i >= 0 & j >= 0){nums1[-- p] = nums1[i] < nums2[j] ? nums2[j --] : nums1[i --];} while(j >= 0){nums1[-- p] = nums2[j --];}}
};

反思

nums1[i + j] = nums2[j --]
执行这条命令的时候,nums1[i+j]当中的j会取减1之后的值。

#include<iostream>
#include<vector>
using namespace std;int main(){vector<int> nums = {0, 1, 2, 3, 4};vector<int> nums2 = {0, 0, 0, 0, 0};int i = nums.size() - 1;while(i >= 0){nums2[i] = nums[i --];}for(int j = 0; j < 5; j ++) cout << nums2[j] << " ";return 0;
}

如果i取值为–之前的值,那么输出结果应该为0 1 2 3 4
实际实验输出结果为1 2 3 4 0,证明C++会依次进行取值,变量自减,最后赋值的操作。赋值(=)的优先级一定是最低的。

http://www.dtcms.com/a/286800.html

相关文章:

  • 策略模式+工厂模式(案例实践易懂版)
  • 半小时部署本地deepseek【1】
  • HTTP/2:突破性能瓶颈的Web传输革命
  • 低代码可视化工作流的系统设计与实现路径研究
  • 开启modbus tcp模拟调试
  • C++并发编程-14. 利用栅栏实现同步
  • 嵌入式系统内核镜像相关(十六)
  • Vue中使用vue-3d-model实现加载3D模型预览展示
  • docker命令参数详解
  • 数字化转型:概念性名词浅谈(第三十二讲)
  • 基础密码协议
  • Python os 模块:系统操作的 “百宝箱”
  • Java编程规范(简约版)
  • MoE,混合专家
  • pycharm结构查看器
  • 世界有色金属杂志世界有色金属杂志社世界有色金属编辑部2025年第9期目录
  • WAF能够解决数据库被渗透的问题吗?
  • Redis-集群与分区
  • 5W8-3D牢游戏超级大集合[2012年6月] 地址 + 解压密码
  • 更适合后端宝宝的前端三件套之HTML
  • 光伏系统优化布局,实现从空间利用到效能的最大化
  • 2-大语言模型—理论基础:详解Transformer架构的实现(2)
  • Redisson 分布式锁
  • 一小时学习Redis
  • 使用 jar -xvf 解压JAR文件无反应怎么办?
  • Maven私服仓库,发布jar到私服仓库,依赖的版本号如何设置,规范是什么
  • 帆软可视化图
  • mave手动下载某个依赖,到本地库
  • 更适合后端宝宝的前端三件套之JavaScript
  • /字符串/