-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path88. Merge Sorted Array
69 lines (45 loc) · 1.47 KB
/
88. Merge Sorted Array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*Runtime: 0 ms, faster than 100.00% of Java online submissions for Merge Sorted Array.
Memory Usage: 38.8 MB, less than 96.05% of Java online submissions for Merge Sorted Array.*/
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int[] nums3=new int[m+n-1];
for (int i=0; i<nums3.length; i++)
nums3[i] =nums1[i];
if(n==0)
return;
int i=0,j=0,k=0;
while(i<m && j<n)
{
if(nums3[i]<=nums2[j])
nums1[k++]= nums3[i++];
else
nums1[k++]= nums2[j++];
}
while(i<m)
{
nums1[k++]=nums3[i++];
}
while(j<n)
{
nums1[k++]=nums2[j++];
}
}
}
/*
second approach
Runtime: 0 ms, faster than 100.00% of Java online submissions for Merge Sorted Array.
Memory Usage: 38.9 MB, less than 89.90% of Java online submissions for Merge Sorted Array.*/
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int i=m-1, j=n-1, k=m+n-1;
while(i>=0 && j>=0)
{
if(nums1[i]>=nums2[j])
nums1[k--]=nums1[i--];
else
nums1[k--]=nums2[j--];
}
while(j>=0)
nums1[k--]=nums2[j--];
}
}