leetcode:(88)Merge Sorted Array(java)
阿新 • • 發佈:2018-12-19
題目:
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
- The number of elements initialized in nums1 and nums2 are m and n respectively.
- You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2
Example:
Input: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6]
解題思路:
從尾像頭遍歷,用兩個指標分別指向兩個陣列的最後一個元素(注意:陣列1是指向最後一個非空元素)。如果1中的元素遍歷完,則將2中的元素複製到陣列中。如果2中的元素遍歷完,則將1中的元素直接複製到陣列中。具體程式碼如下:
package Leetcode_Github; public class TwoPoints_Merge_88_1104 { public void Merge(int[] nums1, int m, int[] nums2, int n) { int index1 = m - 1; int index2 = n - 1; int MergeIndex = m + n - 1; while (index1 >= 0 || index2 >= 0) { //index1和index2的判斷要放在前面,防止空指標 if (index1 < 0) { nums1[MergeIndex--] = nums2[index2--]; } else if (index2 < 0) { nums1[MergeIndex--] = nums1[index1--]; } else if (nums1[index1] < nums2[index2]) { nums1[MergeIndex--] = nums2[index2--]; } else { nums1[MergeIndex--] = nums1[index1--]; } } } }