我在https://leetcode.com/problems/merge-sorted-array/description/中看到了这个,答案在https://leetcode.com/problems/merge-sorted-array/discuss/29503/漂亮的 Python 解决方案
def merge(self, nums1, m, nums2, n):
while m > 0 and n > 0:
if nums1[m-1] >= nums2[n-1]:
nums1[m+n-1] = nums1[m-1]
m -= 1
else:
nums1[m+n-1] = nums2[n-1]
n -= 1
if n > 0:
nums1[:n] = nums2[:n]
我有两个疑问:
print(Solution().merge([1, 2, 3], 3,
[4, 5, 6], 3))
,它只是给了我一个错误提示IndexError: list
assignment index out of range
。问题就在这里:
def merge(self, nums1, m, nums2, n):
while m > 0 and n > 0:
if nums1[m-1] >= nums2[n-1]:
nums1[m+n-1] = nums1[m-1] # nums1[m+n-1] IndexError
m -= 1
else:
nums1[m+n-1] = nums2[n-1] # Same as above
n -= 1
if n > 0:
nums1[:n] = nums2[:n]
您可能需要先“调整”列表大小以防止索引错误:
def merge(self, nums1, m, nums2, n):
nums1 += nums2
# Or nums1 += [None] * len(nums2)
while m > 0 and n > 0:
if nums1[m-1] >= nums2[n-1]:
nums1[m+n-1] = nums1[m-1] # nums1[m+n-1] IndexError
m -= 1
else:
nums1[m+n-1] = nums2[n-1] # Same as above
n -= 1
if n > 0:
nums1[:n] = nums2[:n]
def merge_two_sorted_arrays(left: list, right: list) -> list:
"""
Merge Sorted Array in leetcode
Args:
left: left array
right: right array
Returns: A new merged array
"""
A = [None] * (len(left) + len(right))
i = j = k = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
A[k] = left[i]
i += 1
else:
A[k] = right[j]
j += 1
k += 1
while i < len(left):
A[k] = left[i]
i += 1
k += 1
while j < len(right):
A[k] = right[j]
j += 1
k += 1
return A
a = [1, 2, 2, 4]
b = [3, 5, 6, 9]
print(merge_two_sorted_arrays(a, b))
输出:
[1, 2, 2, 3, 4, 5, 6, 9]
合并两个已排序数组的Java代码
给定两个已排序的数组,任务是以排序的方式合并它们。
输入:arr1[] = { 1, 3, 4, 5},arr2[] = {2, 4, 6, 8} 输出:arr3[] = {1, 2, 3, 4, 4, 5, 6, 8}
输入:arr1[] = { 5, 8, 9},arr2[] = {4, 7, 8} 输出:arr3[] = {4, 5, 7, 8, 8, 9}
尝试使用两个输入数组的不同组合并比较预期数组
导入java.util.Arrays;
公共类 MergeArraysDemo {
public static void main(String[] args) {
int arr1[] = { 1, 3, 5, 7 };
int arr2[] = { 2, 4, 6, 8 };
// int arr1[] = { 5, 8, 9 };
// int arr2[] = { 4, 7, 8 };
int arr3[] = mergeArrays(arr1, arr2);
System.out.println("Array after merging - " + Arrays.toString(arr3));
}
public static int[] mergeArrays(int[] arr1, int[] arr2) {
int n = arr1.length;
int m = arr2.length;
int[] arr3 = new int[n + m];
int j = 0;
int k = 0;
int min = 0;
// max = Integer.MAX_VALUE;
boolean flg = false;
for (int i = 0; i < n + m; i++) {
if (j < n && k < m) {
min = arr2[k];
if (arr1[j] <= min) {
arr3[i] = arr1[j];
j++;
flg = false;
} else {
arr3[i] = min;
k++;
flg = true;
}
} else {
if (flg) {
arr3[i] = arr1[n - 1];
} else {
arr3[i] = min;
}
}
}
return arr3;
}
}