天天看點

Merge Sorted Array @LeetCode

package Level2;

import java.util.Arrays;

/**
 * Merge Sorted Array
 * 
 *  Given two sorted integer arrays A and B, merge B into A as one sorted array.

Note:
You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
 *
 */
public class S88 {

	public static void main(String[] args) {
		int[] A = {1,2,3,0,0,0,0};
		int[] B = {4,5,6,0,0,0};
		merge(A, 3, B, 3);
		System.out.println(Arrays.toString(A));
	}
	
	// 合并兩個有序數組,從尾到頭合并
	public static void merge(int A[], int m, int B[], int n) {
        int i = m-1, j = n-1;		// i指向A的有效末尾,j指向B的有效末尾
        int k = m+n-1;			// k指向合并後A的末尾
        
        // 當兩個數組都有數時,比較合并
        while(i>=0 && j>=0){
        	if(A[i] >= B[j]){
        		A[k] = A[i];
        		i--;
        	}else{
        		A[k] = B[j];
        		j--;
        	}
        	k--;
        }
        
        // 如果有其中一個數組剩下,就直接合并
        while(i >= 0){
        	A[k] = A[i];
        	i--;
        	k--;
        }
        while(j >= 0){
        	A[k] = B[j];
        	j--;
        	k--;
        }
        
    }

}