Algorithm Of Swift -- 4.合并两个有序数组

题目描述:

        给你两个有序整数数组 nums1nums2,请你将 nums2 合并到 nums1 中,使 nums1 成为一个有序数组。
     说明:
        初始化 nums1nums2 的元素数量分别为 mn
        你可以假设 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])
    }
}
原文地址:https://www.cnblogs.com/zongqingmeng/p/14145460.html