原题链接在这里:https://leetcode.com/problems/merge-sorted-array/
从后往前,比较A 和 B 两个数组,谁的大谁就放在最后面。
Time Complexity: O(n). Space: O(1).
AC Java:
1 public class Solution { 2 public void merge(int A[], int m, int B[], int n) { 3 //put compared result to the last of A, to maintain the unsorted elements in A 4 int pa = m-1; 5 int pb = n-1; 6 int pc = m+n-1; 7 8 for(;pc>=0;pc--){ 9 //Remember to check if index pa is out of bound FIRST!!! 10 //This part is super tricky, second is check if pb is out of bound 11 //The order of three comparison could not be exchanged 12 //If pa is out of bound, A[pa]>B[pb] will give error since A[-1] is not accepted 13 //If pb is out of bound, A[pa]>B[pb] will give error since B[-1] is not accepted 14 //So check pa and pb FIRST 15 if(pa>=0 && ( pb<0 || A[pa]>B[pb])){ 16 A[pc] = A[pa--]; 17 }else{ 18 A[pc] = B[pb--]; 19 } 20 } 21 } 22 }
原文:http://www.cnblogs.com/Dylan-Java-NYC/p/4980297.html