Skip to content

Latest commit

 

History

History
25 lines (21 loc) · 736 Bytes

88.合并两个有序数组.md

File metadata and controls

25 lines (21 loc) · 736 Bytes

方法一:双指针

image-20211212144347131

两个数组从后往前扫描,将更大的值放入到第一个数组中

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int pt1 = m - 1, pt2 = n - 1;
        for (int i = nums1.length - 1; i >= 0; i--) {
            int num1 = pt1 >= 0 ? nums1[pt1] : Integer.MIN_VALUE;
            int num2 = pt2 >= 0 ? nums2[pt2] : Integer.MIN_VALUE;
            if (num1 >= num2) {
                nums1[i] = num1;
                pt1--;
            } else {
                nums1[i] = num2;
                pt2--;
            }
        }
    }
}