-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergeSortedArray.js
More file actions
50 lines (46 loc) · 1.44 KB
/
mergeSortedArray.js
File metadata and controls
50 lines (46 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* LeetCode 88. Merge Sorted Array
* https://leetcode.com/problems/merge-sorted-array/
*
* You are given two integer arrays nums1 and nums2, sorted in non-decreasing
* order, and two integers m and n, representing the number of elements in
* nums1 and nums2 respectively.
*
* Merge nums2 into nums1 as one sorted array. The final sorted array should
* not be returned by the function, but instead be stored inside nums1.
* To accommodate this, nums1 has a length of m + n, where the first m elements
* denote the elements that should be merged, and the last n elements are 0
* and should be ignored.
*/
/**
* @param {number[]} nums1
* @param {number} m
* @param {number[]} nums2
* @param {number} n
* @return {void}
*/
function merge(nums1, m, nums2, n) {
// 1. Initialize three pointers
let p1 = m - 1; // Pointer for the last valid element in nums1
let p2 = n - 1; // Pointer for the last element in nums2
let p = m + n - 1; // Pointer for the last position in nums1
// 2. Iterate while there are elements to compare in both arrays
while (p1 >= 0 && p2 >= 0) {
if (nums1[p1] > nums2[p2]) {
nums1[p] = nums1[p1];
p1--;
} else {
nums1[p] = nums2[p2];
p2--;
}
p--;
}
// 3. If elements remain in nums2, copy them over
// (If elements remain in nums1, they are already in the correct place)
while (p2 >= 0) {
nums1[p] = nums2[p2];
p2--;
p--;
}
}
module.exports = { merge };