Skip to content

Commit ae1a8fc

Browse files
committed
update
1 parent 32b7af2 commit ae1a8fc

File tree

2 files changed

+67
-6
lines changed

2 files changed

+67
-6
lines changed

leetcode_solved/leetcode_0088_Merge_Sorted_Array.cpp

Lines changed: 0 additions & 6 deletions
This file was deleted.
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
* AC: T:O(m+n) S:O(m+n)
3+
* Runtime: 0 ms, faster than 100.00% of Java online submissions for Merge Sorted Array.
4+
* Memory Usage: 38.8 MB, less than 89.83% of Java online submissions for Merge Sorted Array.
5+
*
6+
* 双指针法:可从头部开始,也可以从尾部开始
7+
*
8+
* 备选较差思路:合并后大数组排序,T:O((m+n)log(m+n)), S:O(log(m+n))
9+
*/
10+
/**
11+
description:
12+
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
13+
14+
The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has a size equal to m + n such that it has enough space to hold additional elements from nums2.
15+
16+
17+
Example 1:
18+
19+
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
20+
Output: [1,2,2,3,5,6]
21+
Example 2:
22+
23+
Input: nums1 = [1], m = 1, nums2 = [], n = 0
24+
Output: [1]
25+
26+
27+
Constraints:
28+
29+
nums1.length == m + n
30+
nums2.length == n
31+
0 <= m, n <= 200
32+
1 <= m + n <= 200
33+
-109 <= nums1[i], nums2[i] <= 109
34+
*
35+
*/
36+
class Solution {
37+
public static void merge(int[] nums1, int m, int[] nums2, int n) {
38+
int p1 = 0, p2 = 0, retP = 0;
39+
int[] ret = new int[m + n];
40+
while (p1 != m && p2 != n) {
41+
if (nums1[p1] < nums2[p2]) {
42+
ret[retP] = nums1[p1];
43+
p1++;
44+
} else {
45+
ret[retP] = nums2[p2];
46+
p2++;
47+
}
48+
retP++;
49+
}
50+
if (p1 != m) { // 数组1有尾部
51+
while(p1 != m) {
52+
ret[retP] = nums1[p1];
53+
retP++;
54+
p1++;
55+
}
56+
}
57+
if (p2 != n) { // 数组2有尾部
58+
while(p2 != n) {
59+
ret[retP] = nums2[p2];
60+
retP++;
61+
p2++;
62+
}
63+
}
64+
65+
System.arraycopy(ret, 0, nums1, 0, m + n);
66+
}
67+
}

0 commit comments

Comments
 (0)