給定兩個有序整數數組 nums1 和 nums2,將 nums2 合併到 nums1 中,使得 num1 成爲一個有序數組。數組
說明:spa
示例:指針
輸入: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3
輸出: [1,2,2,3,5,6]
兩個指針分別指向num1和num2的尾元素,一個結果指針指向結果數組尾(即num1),每次比較兩指針較大元素,放到結果指針位置。每輪較大元素指針和結果指針向前移動,直到結果指針到數組首。code
public class P088 { public void merge(int[] nums1, int m, int[] nums2, int n) { int indec1 = m - 1; int indec2 = n - 1; int indec = m + n - 1; while (indec >= 0) { if (indec1 < 0) { nums1[indec--] = nums2[indec2--]; } else if (indec2 < 0) { nums1[indec--] = nums1[indec1--]; } else if (nums1[indec1] > nums2[indec2]) { nums1[indec--] = nums1[indec1--]; } else { nums1[indec--] = nums2[indec2--]; } } } }