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++会依次进行取值,变量自减,最后赋值的操作。赋值(=)的优先级一定是最低的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ayu阿予

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值