Skip to content

Latest commit

 

History

History
47 lines (31 loc) · 724 Bytes

File metadata and controls

47 lines (31 loc) · 724 Bytes

Merge Sorted Array

Problem Link

https://leetcode.com/problems/merge-sorted-array/


Pattern

  • Two Pointer
  • In-place

Approach

Merge from the end using three pointers: one at the end of each array and one at the end of the merged space, placing larger elements first.


Time Complexity

O(m + n)

Space Complexity

O(1)


Java Solution

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int i = m - 1, j = n - 1, k = m + n - 1;
        while (j >= 0) {
            if (i >= 0 && nums1[i] > nums2[j]) {
                nums1[k--] = nums1[i--];
            } else {
                nums1[k--] = nums2[j--];
            }
        }
    }
}