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