> For the complete documentation index, see [llms.txt](https://emmaguo100.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://emmaguo100.gitbook.io/leetcode/01-15-2022-88.md).

# 01/15/2022 88

method 1: brutal force

write the number of the values in nums2 into nums1 with the position of i + m, then sort the nums1

Time Compelxity O((n+m) log(n+m)) Space: O(n)

public void merge(int\[] nums1, int m, int\[] nums2, int n) {

```
    //brutal force
    
    for (int i = 0; i < n; i++){
        nums1[i + m] = nums2[i];
    }
    Arrays.sort(nums1);
    
}
```

method 2: start from end to start three pointers

&#x20;set `p1` to point at index `m - 1` of `nums1`, `p2` to point at index `n - 1` of `nums2`, and `p` to point at index `m + n - 1` of `nums1. if nums1 > nums2, set nums[p] = nums1[p1]. p1--; else nums[p] = nums2[p2]. p2--.`

`Time O(n+m)`

`Space o(1)`

class Solution { public void merge(int\[] nums1, int m, int\[] nums2, int n) {&#x20;

// Set p1 and p2 to point to the end of their respective arrays.

&#x20;int p1 = m - 1; int p2 = n - 1;

```
    // And move p backwards through the array, each time writing
    // the bigger value pointed at by p1 or p2.
    for (int p = m + n - 1; p >= 0; p--) {
        if (p2 < 0) {
            break;
        }
        if (p1 >= 0 && nums1[p1] > nums2[p2]) {
            nums1[p] = nums1[p1--];
        } else {
            nums1[p] = nums2[p2--];
        }
    }
}
```

}
