Merge Sorted Array LeetCode solution in Java

1
class Solution {
2
public void merge(int[] nums1, int m, int[] nums2, int n) {
3
// Initialize i and j to store indices of the last element of 1st and 2nd array respectively...
4
int i = m - 1, j = n - 1;
5
// Initialize a variable k to store the last index of the 1st array...
6
int k = m + n - 1;
7
// Create a loop until either of i or j becomes zero...
8
while (i >= 0 && j >= 0) {
9
if (nums1[i] >= nums2[j]) {
10
nums1[k] = nums1[i];
11
i--;
12
} else {
13
nums1[k] = nums2[j];
14
j--;
15
}
16
k--;
17
// Either of i or j is not zero, which means some elements are yet to be merged.
18
// Being already in a sorted manner, append them to the 1st array in the front.
19
}
20
// While i does not become zero...
21
while (i >= 0) nums1[k--] = nums1[i--];
22
// While j does not become zero...
23
while (j >= 0) nums1[k--] = nums2[j--];
24
// Now 1st array has all the elements in the required sorted order...
25
return;
26
}
27
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0