提交 8f09fb09 编写于 作者: GreyZeng's avatar GreyZeng

merge two sorted list

上级 f84e8bd5
package git.snippet.leetcode;
// Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
//
// Note:
//
// The number of elements initialized in nums1 and nums2 are m and n respectively.
// You may assume that nums1 has enough space (size that is equal to m + n) to hold additional
// elements from nums2.
// Example:
//
// Input:
// nums1 = [1,2,3,0,0,0], m = 3
// nums2 = [2,5,6], n = 3
//
// Output: [1,2,2,3,5,6]
//
//
// Constraints:
//
// -10^9 <= nums1[i], nums2[i] <= 10^9
// nums1.length == m + n
// nums2.length == n
// https://leetcode.cn/problems/merge-sorted-array/
// 笔记:
public class LeetCode_0088_MergeSortedArray {
// 从尾部开始处理
public void merge(int[] nums1, int m, int[] nums2, int n) {
int len = m + n;
while (m > 0 && n > 0) {
if (nums1[m - 1] > nums2[n - 1]) {
nums1[--len] = nums1[--m];
} else {
nums1[--len] = nums2[--n];
}
}
while (n > 0) {
nums1[--len] = nums2[--n];
}
}
}
package git.snippet.mergesort;
// 合并两个有序数组
// https://leetcode.com/problems/merge-sorted-array/
// 笔记:https://www.cnblogs.com/greyzeng/p/16653063.html
/**
* @see LintCode_0006_MergeTwoSortedArrays
*/
public class LeetCode_0088_MergeSortedArray {
// 逆向遍历
// 谁大到最后一个位置
// 依次递减
public void merge(int[] nums1, int m, int[] nums2, int n) {
int i = m - 1;
int j = n - 1;
int index = m + n - 1;
while (i >= 0 && j >= 0) {
nums1[index--] = nums1[i] < nums2[j] ? nums2[j--] : nums1[i--];
}
while (j >= 0) {
// 只需要继续判断 nums2 了
// 因为 nums1 自然拍好了
nums1[index--] = nums2[j--];
}
}
}
package git.snippet.binarysearch;
package git.snippet.mergesort;
// How can you optimize your algorithm if one array is very large and the other is very small?
// https://www.lintcode.com/problem/6/
// 笔记:https://www.cnblogs.com/greyzeng/p/16653063.html
public class LintCode_0006_MergeTwoSortedArrays {
// 常规解法
// 借鉴归并排序方法
public static int[] mergeSortedArray1(int[] A, int[] B) {
int m = A.length;
int n = B.length;
......@@ -13,11 +14,7 @@ public class LintCode_0006_MergeTwoSortedArrays {
int j = 0;
int index = 0;
while (i < m && j < n) {
if (A[i] > B[j]) {
res[index++] = B[j++];
} else {
res[index++] = A[i++];
}
res[index++] = A[i] > B[j] ? B[j++] : A[i++];
}
while (i < m) {
res[index++] = A[i++];
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册