leetCode-Merge Sorted Array
阿新 • • 發佈:2017-11-26
number int ret script tty style elements scrip clas
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--]; } }
leetCode-Merge Sorted Array