Skip to content

Commit

Permalink
Refactor MergeSortedArray.java
Browse files Browse the repository at this point in the history
  • Loading branch information
huangsam committed Nov 10, 2024
1 parent 8757937 commit 238b49d
Showing 1 changed file with 7 additions and 12 deletions.
19 changes: 7 additions & 12 deletions java/MergeSortedArray.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,13 @@ public void merge(int[] nums1, int m, int[] nums2, int n) {
if (n == 0) {
return;
}
int n1_index = m - 1;
int n2_index = n - 1;
int reverse = m + n - 1;
while (n1_index >= 0 && n2_index >= 0) {
if (nums1[n1_index] > nums2[n2_index]) {
nums1[reverse--] = nums1[n1_index--];
} else {
nums1[reverse--] = nums2[n2_index--];
}
}
while (n2_index >= 0) {
nums1[reverse--] = nums2[n2_index--];
int firstIndex = m - 1;
int secondIndex = n - 1;
int mergeIndex = m + n - 1;
while (secondIndex >= 0) {
nums1[mergeIndex--] = (firstIndex >= 0 && nums1[firstIndex] > nums2[secondIndex])
? nums1[firstIndex--]
: nums2[secondIndex--];
}
}
}

0 comments on commit 238b49d

Please sign in to comment.