###### tags: `LeetCode`,`Java`,`Easy` # Easy-88. Merge Sorted Array ### **題目連結:** [**Merge Sorted Array**](https://leetcode.com/problems/merge-sorted-array/description/) ### **解題方向1** * 將 nums1 數組的前 m 個元素複製到 nums1B 數組中。 * 使用兩個指針 temp1 和 temp2,分別指向 nums1B 和 nums2 數組的開頭。 * 遍歷 nums1 數組,將 nums1B 和 nums2 中小的元素逐一放入 nums1 數組中。 * 遍歷完 nums1B 或 nums2 中的元素後,將 nums1 數組剩餘的位置填入另一個數組中的元素。 ### **完整程式碼1** ```java= import java.util.*; class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { int temp1=0; int temp2=0; int nums1B[]=Arrays.copyOf(nums1, m); for(int i=0;i<m+n;i++){ if(temp1<m && temp2<n){ if(nums2[temp2]<=nums1B[temp1]){ nums1[i]=nums2[temp2]; temp2+=1; }else{ nums1[i]=nums1B[temp1]; temp1+=1; } }else if(temp1>=m){ nums1[i]=nums2[temp2]; temp2+=1; }else if(temp2>=n){ nums1[i]=nums1B[temp1]; temp1+=1; } } } } ``` ### **解題方向2** * 從 nums1 和 nums2 數組的末尾開始比較元素大小。 * 將較大的元素放入 nums1 數組的末尾,並將對應指針向前移動。 * 若其中一個數組的元素已全部放入 nums1 中,則直接將另一個數組的元素依次放入 nums1 中的剩餘位置。 ### **完整程式碼2** ```java= class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { for(int i=m+n-1;i>=0;i--){ if(m==0){ nums1[i]=nums2[n-1]; n--; continue; }else if(n==0){ break; } if(nums2[n-1]>nums1[m-1]){ nums1[i]=nums2[n-1]; n--; }else{ nums1[i]=nums1[m-1]; m--; } } } } ``` ### **解法比較** 第一種解法: 時間複雜度:O(m + n),其中 m 和 n 分別為兩個數組的長度。 空間複雜度:O(m),需要使用一個額外的數組 nums1B,其長度為 m。 第二種解法: 時間複雜度:O(m + n),其中 m 和 n 分別為兩個數組的長度。 空間複雜度:O(1),只需要使用固定數量的變量。 綜合來看,第二種解法的空間複雜度更優,且兩種解法的時間複雜度相同,因此第二種解法為最佳解。