Algorithm Of Swift -- 4.合併兩個有序陣列
阿新 • • 發佈:2020-12-16
題目描述:
給你兩個有序整數陣列 nums1 和 nums2,請你將 nums2 合併到 nums1 中,使 nums1 成為一個有序陣列。
說明:
初始化 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: func merge(_ nums1: inout [Int], _ m: Int, _ nums2: [Int], _ n: Int) { nums1 = (nums1[0..<m] + nums2).sorted() }
解法2:用時最少 func merge(_ nums1: inout [Int], _ m: Int, _ nums2: [Int], _ n: Int) { // 初始化三個指標 var index1 = m - 1 // 表示第一個陣列最後元素的下標 var index2 = n - 1 // 表示第二個陣列最後元素的下標 var currentIndex = nums1.count - 1 // 表示當前放置元素的下標 // 當 index2 < 0 時,就說明第二個陣列中的元素全部合併到了第一個陣列 while index2 >= 0 { if (index1 >= 0 && (nums2[index2] < nums1[index1])) { nums1[currentIndex] = nums1[index1] index1 = index1 - 1 currentIndex = currentIndex - 1 }else { // index1 < 0 || nums2[index2] >= nums1[index1] nums1[currentIndex] = nums2[index2] index2 = index2 - 1 currentIndex = currentIndex - 1 } } }
解法3:記憶體消耗最少 func merge(_ nums1: inout [Int], _ m: Int, _ nums2: [Int], _ n: Int) { // 雙指標 var c1 = m - 1 var c2 = n - 1 var index = m + n - 1 while c1 >= 0 && c2 >= 0 { if nums1[c1] > nums2[c2] { nums1[index] = nums1[c1] c1 -= 1 } else { nums1[index] = nums2[c2] c2 -= 1 } index -= 1 } if c2 >= 0 { nums1.replaceSubrange(0..<c2 + 1, with: nums2[0..<c2 + 1]) } }