Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 54c43fc

Browse files
commit
1 parent 35d7877 commit 54c43fc

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

‎4. Median of Two Sorted Arrays.cpp

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution {
2+
public:
3+
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
4+
int n = nums1.size(), m = nums2.size();
5+
int total = n + m;
6+
int mid = total / 2;
7+
8+
int i = 0, j = 0;
9+
int prev = 0, curr = 0;
10+
11+
for (int k = 0; k <= mid; ++k) {
12+
prev = curr;
13+
14+
if (i < n && (j >= m || nums1[i] <= nums2[j])) {
15+
curr = nums1[i++];
16+
} else {
17+
curr = nums2[j++];
18+
}
19+
}
20+
21+
// If total length is odd
22+
if (total % 2 == 1) return curr;
23+
// If total length is even
24+
return (prev + curr) / 2.0;
25+
26+
27+
}
28+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /