LeetCode - Algorithms - 88. Merge Sorted Array

Problem

88. Merge Sorted Array

Java

1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
if (m == 0) {
for (int i = 0; i < n; i++)
nums1[i] = nums2[i];
return;
}
int idx = m + n - 1;
int idx1 = m - 1, idx2 = n - 1;
for (; idx1 >= 0 && idx2 >= 0; ) {
if (nums1[idx1] < nums2[idx2]) {
nums1[idx--] = nums2[idx2];
idx2--;
} else {
nums1[idx--] = nums1[idx1];
idx1--;
}
}
if (idx2 >= 0)
for (int i = 0; i <= idx2; i++)
nums1[i] = nums2[i];
}
}

Submission Detail

  • 59 / 59 test cases passed.
  • Runtime: 0 ms, faster than 100.00% of Java online submissions for Merge Sorted Array.
  • Memory Usage: 39.9 MB, less than 18.03% of Java online submissions for Merge Sorted Array.

2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
if (m == 0) {
for (int i = 0; i < n; i++)
nums1[i] = nums2[i];
return;
}
int idx = m + n - 1;
m--;
n--;
for (; m >= 0 && n >= 0; ) {
if (nums1[m] < nums2[n]) {
nums1[idx--] = nums2[n];
n--;
} else {
nums1[idx--] = nums1[m];
m--;
}
}
if (n >= 0)
for (int i = 0; i <= n; i++)
nums1[i] = nums2[i];
}
}

Submission Detail

  • 59 / 59 test cases passed.
  • Runtime: 0 ms, faster than 100.00% of Java online submissions for Merge Sorted Array.
  • Memory Usage: 40 MB, less than 14.13% of Java online submissions for Merge Sorted Array.