leetcode88--合并两个有序数组

1. 题意

将两个非逆序合并到其中一个中来。

合并两个有序数组

2. 题解

2.1 合并排序

先将另个数组的值放在前面数组的末尾,再对数组进行排序。

cpp 复制代码
class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {


        copy(nums2.begin(), nums2.end(), nums1.begin() + m);
        sort(nums1.begin(), nums1.end(), less<int>());


    }
};
// Time: O(ologn) Space: O(m+n)
2.2 双指针加辅助数组
cpp 复制代码
class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        vector<int> aux(m + n, 0);

        int p  = 0;
        int p1 = 0;
        int p2 = 0;


        while (p1 < m || p2 < n) {  
            if ( p1 < m && p2 < n) {
                aux[p++] = nums1[p1] <= nums2[p2] ?
                    nums1[p1++] : nums2[p2++];
            }
            else {
                aux[p++] = p1 < m ? nums1[p1++] : nums2[p2++];
            }
        }

        copy(aux.begin(), aux.end(), nums1.begin());
        for(auto c:aux)
            std::cout << c << " ";

    }
};
2.3 双指针加逆序优化空间
cpp 复制代码
class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {


        copy(nums2.begin(), nums2.end(), nums1.begin() + m);
        sort(nums1.begin(), nums1.end(), less<int>());


    }
};
相关推荐
数模竞赛Paid answer19 小时前
2025年MathorCup数学建模A题汽车风阻预测解题文档与程序
算法·数学建模·mathorcup
xin_nai19 小时前
LeetCode热题100(Java)(6)矩阵
java·leetcode·矩阵
Old Uncle Tom1 天前
OpenClaw 记忆系统 -- 记忆预加载
java·数据结构·算法·agent
会编程的土豆1 天前
洛谷题单入门1 顺序结构
数据结构·算法·golang
生信碱移1 天前
PACells:这个方法可以鉴定疾病/预后相关的重要细胞亚群,作者提供的代码流程可以学习起来了,甚至兼容转录组与 ATAC 两种数据类型!
人工智能·学习·算法·机器学习·数据挖掘·数据分析·r语言
智者知已应修善业1 天前
【51单片机中的打飞机设计】2023-8-25
c++·经验分享·笔记·算法·51单片机
圣保罗的大教堂1 天前
leetcode 1855. 下标对中的最大距离 中等
leetcode
智者知已应修善业1 天前
【51单片机按键调节占空比3位数码管显示】2023-8-24
c++·经验分享·笔记·算法·51单片机
.5481 天前
## Sorting(排序算法)
python·算法·排序算法
wuweijianlove1 天前
算法的平均复杂度建模与性能回归分析的技术7
算法·数据挖掘·回归