Swift 3 linear solution


  • 0
    Y
    
    class Solution {
        // merge from end to front, so we dont need extra space
        func merge(_ nums1: inout [Int], _ m: Int, _ nums2: [Int], _ n: Int) {
            var i = m + n - 1, p1 = m - 1, p2 = n - 1
            while p2 >= 0 {
                if p1 >= 0 && nums1[p1] > nums2[p2] {
                    nums1[i] = nums1[p1]
                    p1 -= 1
                } else {
                    nums1[i] = nums2[p2]
                    p2 -= 1
                }
                i -= 1
            }
        }
    }
    
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.