Description:
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
Solution:
//初始化三个指针,i指向A含有元素的尾部,j指向B的尾部,k指向A存放元素的尾部 //对A和B逆序遍历,从两个数组中找出最大元素存放一次放到k指向的位置 //最后看看B有没有放完(不用管A,因为如果i>=0说明剩余元素就该放在原位置上,如果i<0,说明j没有放完,还得继续遍历B) class Solution { public void merge(int A[], int m, int B[], int n) { int i=m-1, j=n-1, k=m+n-1; while (i>-1 && j>-1) A[k--]= (A[i]>B[j]) ? A[i--] : B[j--]; while (j>-1) A[k--]=B[j--]; } }