Skip to content

Commit 05556e4

Browse files
authored
Create merge-sorted-array.cs
1 parent d8d2b87 commit 05556e4

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

C#/merge-sorted-array.cs

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
public class Solution
2+
{
3+
/**
4+
* Merges two sorted arrays in-place.
5+
* @param nums1: First array containing m elements
6+
* @param m: Length of nums1
7+
* @param nums2: Second array containing n elements
8+
* @param n: Length of nums2
9+
*/
10+
public void Merge(int[] nums1, int m, int[] nums2, int n)
11+
{
12+
int last = m + n - 1;
13+
int i = m - 1;
14+
int j = n - 1;
15+
16+
while (i >= 0 && j >= 0)
17+
{
18+
if (nums1[i] > nums2[j])
19+
{
20+
nums1[last] = nums1[i];
21+
last--;
22+
i--;
23+
}
24+
else
25+
{
26+
nums1[last] = nums2[j];
27+
last--;
28+
j--;
29+
}
30+
}
31+
32+
while (j >= 0)
33+
{
34+
nums1[last] = nums2[j];
35+
last--;
36+
j--;
37+
}
38+
}
39+
}
40+
41+
42+
/*** SOLUTION TWO ***/
43+
44+
public class Solution {
45+
public void Merge(int[] nums1, int m, int[] nums2, int n) {
46+
if (n == 0) {
47+
return;
48+
}
49+
50+
if (m == 0) {
51+
for (var i = 0; i < n; i++) {
52+
nums1[i] = nums2[i];
53+
}
54+
return;
55+
}
56+
57+
var end = m + n - 1;
58+
var ind1 = m - 1;
59+
var ind2 = n - 1;
60+
61+
while (end >= 0) {
62+
if (ind1 < 0 && ind2 < 0) {
63+
return;
64+
}
65+
else if (ind1 < 0) {
66+
nums1[end] = nums2[ind2];
67+
ind2--;
68+
}
69+
else if (ind2 < 0) {
70+
nums1[end] = nums1[ind1];
71+
ind1--;
72+
}
73+
else if (nums1[ind1] > nums2[ind2]) {
74+
nums1[end] = nums1[ind1];
75+
ind1--;
76+
} else {
77+
nums1[end] = nums2[ind2];
78+
ind2--;
79+
}
80+
81+
end--;
82+
}
83+
}
84+
}

0 commit comments

Comments
 (0)