【leetcode-88】 合並兩個有序數組
阿新 • • 發佈:2019-03-27
插入 lse while num 說明 空間大小 大於 index 等於
(1過)
給定兩個有序整數數組 nums1 和 nums2,將 nums2 合並到 nums1 中,使得 num1 成為一個有序數組。
說明:
- 初始化 nums1 和 nums2 的元素數量分別為 m 和 n。
- 你可以假設 nums1 有足夠的空間(空間大小大於或等於 m + n)來保存 nums2 中的元素。
示例:
輸入: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 輸出: [1,2,2,3,5,6]
需要註意:
1.歸並排序最後一步,避免數組移動需要從後往前遍歷
2.要考慮A遍歷完B有剩余情況,需要額外把B中元素插入A前部
public void merge(int A[], int m, int B[], int n) { int index = m+n-1; int indexA = m-1; int indexB = n-1; while (index >= 0 && indexA >= 0 && indexB >= 0) { if (A[indexA] > B[indexB]) { A[index] = A[indexA]; index--; indexA--; } else { A[index] = B[indexB]; index--; indexB--; } } if (indexB >= 0) { while (index >=0 && indexB>=0) { A[index] = B[indexB]; index--; indexB--; } } }
【leetcode-88】 合並兩個有序數組