標籤:style blog color java io strong ar for 2014
[ 問題: ]
Given two sorted integer arrays A and B, merge B into A as one sorted array.
直譯:給定兩個排好序的整形數組,將數組B合并到數組A,形成一個新的數組。
Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B.
The number of elements initialized in A and B are m and n respectively.
[ 解法: ]
題解:從結尾開始歸併,不會覆蓋元素又能滿足題意。
參數m:數組m位置後面元素會被數組B中元素替換
參數n:從第一個開始,將數組B中n個元素會被合并到數組A
public class Solution {public static void main(String[] args) {int[] A = { 1, 2, 4, 5, 6, 8 };int[] B = { 3, 9, 10 };new Solution().merge(A, 3, B, 2); // 1 2 3 4 9 8}public void merge(int A[], int m, int B[], int n) {int i, j, k;for (i = m - 1, j = n - 1, k = m + n - 1; k >= 0; --k) {if (i >= 0 && (j < 0 || A[i] > B[j])) {A[k] = A[i--];} else {A[k] = B[j--];}}}}
【LeetCode】- Merge Sorted Array (合并有序數組)