0. ソートされた 2 つの配列をマージします
質問: 2 つの配列 A1 と A2 が昇順に配置されています。A1 の末尾には A2 を収容するのに十分な空き領域があります。A2 のすべての数値を A1 に挿入する関数を実装してください。すべての数値はソートされます。
nums1.length == m + n
nums2.length == n
解決策: この質問は [Sword Finger Offer | 2. Replace Spaces] と似ていますが、配列 (文字列) を結合する場合、各数値を前から後ろに移動する場合、数値を複数回移動する必要があるため、次のように移動することを検討できます。モバイルなので効率が向上します。
1.C言語バージョン
void merge(int* nums1, int nums1Size, int m, int* nums2, int nums2Size, int n){
//目标就是把nums2中的元素挪完-->end2==>0
//下面的deadLine,end1,end2都是对应的下标--双指针
int deadLine=m+n-1;
int end1=m-1;
int end2=n-1;
while(end1>=0&&end2>=0)
{
if(nums1[end1]>nums2[end2])
{
nums1[deadLine--]=nums1[end1--];
}
else
{
nums1[deadLine--]=nums2[end2--];
}
}
//到这里如果end2==0的话,就说明num2挪完了,任务完成了;如果是end1==0的话,直接把nums2中剩余元素挪动到num1中即可
if(end1<0)
{
while(end2>=0)
{
nums1[deadLine--]=nums2[end2--];
}
}
}
文句を言いましょう。このパラメータ num1Size は少し冗長です。
2.C++バージョン
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int deadLine=nums1.size()-1;
int end1=m-1;
int end2=n-1;
while(end1>=0&&end2>=0)
{
if(nums1[end1]>nums2[end2])
{
nums1[deadLine--]=nums1[end1--];
}
else
{
nums1[deadLine--]=nums2[end2--];
}
}
if(end1<0)
{
while(end2>=0)
{
nums1[deadLine--]=nums2[end2--];
}
}
}
};