-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathMergeSortedArray.js
More file actions
87 lines (78 loc) · 2.02 KB
/
Copy pathMergeSortedArray.js
File metadata and controls
87 lines (78 loc) · 2.02 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
* Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
*
* Note:
*
* You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
*
* The number of elements initialized in nums1 and nums2 are m and n respectively.
*
* Accepted.
*/
/**
* @param {number[]} nums1
* @param {number} m
* @param {number[]} nums2
* @param {number} n
* @return {void} Do not return anything, modify nums1 in-place instead.
*/
let merge = function (nums1, m, nums2, n) {
while (n > 0) {
if (m <= 0 || nums1[m - 1] <= nums2[n - 1]) {
nums1[m + n - 1] = nums2[n - 1];
n--;
} else {
nums1[m + n - 1] = nums1[m - 1];
m--;
}
}
};
let array0 = [1];
merge(array0, 1, [], 0);
if (array0.toString() === [1].toString()) {
console.log("pass")
} else {
console.error("failed")
}
let array1 = [0];
merge(array1, 0, [1], 1);
if (array1.toString() === [1].toString()) {
console.log("pass")
} else {
console.error("failed")
}
let array2 = [4, 5, 6, 0, 0, 0];
merge(array2, 3, [1, 2, 3], 3);
if (array2.toString() === [1, 2, 3, 4, 5, 6].toString()) {
console.log("pass")
} else {
console.error("failed")
}
let array3 = [0, 0, 0, 1, 2, 3, -1, -1, -1];
merge(array3, 6, [0, 4], 2);
if (array3.toString() === [0, 0, 0, 0, 1, 2, 3, 4, -1].toString()) {
console.log("pass")
} else {
console.error("failed")
}
let array4 = [0, 1, 2, 3, 0, 0, 0, 0, 0];
merge(array4, 4, [3, 4, 0], 2);
if (array4.toString() === [0, 1, 2, 3, 3, 4, 0, 0, 0].toString()) {
console.log("pass")
} else {
console.error("failed")
}
let array5 = [1, 2, 0, 0];
merge(array5, 2, [1], 1);
if (array5.toString() === [1, 1, 2, 0].toString()) {
console.log("pass")
} else {
console.error("failed")
}
let array6 = [1, 2, 3, 0, 0, 0];
merge(array6, 3, [2, 5, 6], 3);
if (array6.toString() === [1, 2, 2, 3, 5, 6].toString()) {
console.log("pass")
} else {
console.error("failed")
}