java: add «88. Merge Sorted Array»
URL: https://leetcode.com/problems/merge-sorted-array/
This commit is contained in:
parent
ec2d7fe842
commit
8ecf9fb8d8
1 changed files with 25 additions and 0 deletions
25
java/merge-sorted-array.java
Normal file
25
java/merge-sorted-array.java
Normal file
|
@ -0,0 +1,25 @@
|
|||
class Solution {
|
||||
public void merge(int[] nums1, int m, int[] nums2, int n) {
|
||||
// Shift numbers to right
|
||||
for (int i = m - 1, k = nums1.length - 1; i >= 0; --i, --k) {
|
||||
nums1[k] = nums1[i];
|
||||
}
|
||||
|
||||
// Merge them
|
||||
int j = 0, k = 0;
|
||||
for (int i = nums1.length - m; i < nums1.length && j < n; ++k) {
|
||||
if (nums1[i] < nums2[j]) {
|
||||
nums1[k] = nums1[i];
|
||||
++i;
|
||||
} else {
|
||||
nums1[k] = nums2[j];
|
||||
++j;
|
||||
}
|
||||
}
|
||||
|
||||
// Add the remainder
|
||||
for (; j < n; ++j, ++k) {
|
||||
nums1[k] = nums2[j];
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue