[toc]
題目:https://leetcode-cn.com/problems/merge-sorted-array/
要求
合并兩個給你兩個有序整數(shù)數(shù)組 nums1 和 nums2,請你將 nums2 合并到 nums1 中,使 nums1 成為一個有序數(shù)組。
思路
- 雙索引
- 復制一個數(shù)組出來
- 遍歷兩個數(shù)組賦值
代碼
class LeetCode88 {
static List<int> num1Copy = [];
static merge(List<int> nums1, int m, List<int> nums2, int n) {
int num1Index = 0;
int num2Index = 0;
num1Copy.clear();
//備份num1數(shù)組
for (var i = 0; i < m; i++) {
num1Copy.add(nums1[i]);
}
int num1CopyIndex = 0; //記錄備份數(shù)組索引
//兩個數(shù)組都得比較完
while (num2Index < n || num1CopyIndex < m) {
if (num1CopyIndex < m && num2Index < n) {
//正常情況
if (num1Copy[num1CopyIndex] < nums2[num2Index]) {
nums1[num1Index] = num1Copy[num1CopyIndex];
num1CopyIndex += 1;
} else {
nums1[num1Index] = nums2[num2Index];
num2Index += 1;
}
} else {
if (num1CopyIndex < m) {//num1還沒比較完
nums1[num1Index] = num1Copy[num1CopyIndex];
num1CopyIndex += 1;
} else {//num2還沒比較完阿
nums1[num1Index] = nums2[num2Index];
num2Index += 1;
}
}
num1Index += 1;
}
print(nums1);
}
}
main(List<String> args) {
LeetCode88.merge([2, 0], 1, [1], 1);
}
執(zhí)行結(jié)果結(jié)果
[1, 2]