Accepted golang solution O(n), easy pick


  • 0
    V

    I use 'merge' approach from MergeSort for combining two arrays into one.
    Just put at the end of num1 the biggest element from both arrays.
    i > 0 is needed to determine when all items from 1 array are in right places and need only put elements from num2 at the beginning.

    func MergeSortedArrays(nums1 []int, m int, nums2 []int, n int) {
    	j := n - 1
    	i := m - 1
    	putIndex := m + n - 1
    	for j >= 0 {
    		if i < 0 || nums2[j] > nums1[i] {
    			nums1[putIndex] = nums2[j]
    			j--
    		} else {
    			nums1[putIndex] = nums1[i]
    			i--
    		}
    		putIndex--
    	}
    }
    

Log in to reply
 

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