Skip to content

Commit 1c166df

Browse files
committed
solve 88: merge sorted array
1 parent 8b29947 commit 1c166df

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

vscode/88.merge-sorted-array.java

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
* @lc app=leetcode id=88 lang=java
3+
*
4+
* [88] Merge Sorted Array
5+
*
6+
* https://leetcode.com/problems/merge-sorted-array/description/
7+
*
8+
* algorithms
9+
* Easy (34.87%)
10+
* Total Accepted: 348K
11+
* Total Submissions: 985.6K
12+
* Testcase Example: '[1,2,3,0,0,0]\n3\n[2,5,6]\n3'
13+
*
14+
* Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as
15+
* one sorted array.
16+
*
17+
* Note:
18+
*
19+
*
20+
* The number of elements initialized in nums1 and nums2 are m and n
21+
* respectively.
22+
* You may assume that nums1 has enough space (size that is greater or equal to
23+
* m + n) to hold additional elements from nums2.
24+
*
25+
*
26+
* Example:
27+
*
28+
*
29+
* Input:
30+
* nums1 = [1,2,3,0,0,0], m = 3
31+
* nums2 = [2,5,6], n = 3
32+
*
33+
* Output: [1,2,2,3,5,6]
34+
*
35+
*
36+
*/
37+
class Solution {
38+
public void merge(int[] nums1, int m, int[] nums2, int n) {
39+
int i = m - 1;
40+
int j = n - 1;
41+
int k = m + n - 1;
42+
43+
while (i >= 0 && j >= 0) {
44+
nums1[k--] = (nums1[i] > nums2[j]) ? nums1[i--] : nums2[j--];
45+
}
46+
47+
while (j >= 0) {
48+
nums1[k--] = nums2[j--];
49+
}
50+
}
51+
}
52+

0 commit comments

Comments
 (0)