Skip to content

Commit 00eff09

Browse files
authored
Create Median-of-Two-Sorted-Array.java
This is a fundamental problem, and the algorithm I used clearly illustrates the approach to solving this type of question.
1 parent e499d3b commit 00eff09

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
//Median of Two Sorted Arrays
2+
3+
//Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
4+
5+
//Example 1:
6+
7+
//Input: nums1 = [1,3], nums2 = [2]
8+
//Output: 2.00000
9+
//Explanation: merged array = [1,2,3] and median is 2.
10+
11+
//Example 2:
12+
13+
//Input: nums1 = [1,2], nums2 = [3,4]
14+
//Output: 2.50000
15+
//Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
16+
17+
//Constraints:
18+
19+
//nums1.length == m
20+
//nums2.length == n
21+
//0 <= m <= 1000
22+
//0 <= n <= 1000
23+
//1 <= m + n <= 2000
24+
//-106 <= nums1[i], nums2[i] <= 106
25+
26+
//Solution
27+
28+
class Solution {
29+
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
30+
int m=nums1.length;
31+
int n=nums2.length;
32+
int [] res=new int[m+n];
33+
int i=0,j=0,k=0;
34+
while(i<m&&j<n){
35+
if(nums1[i]<nums2[j]){
36+
res[k]=nums1[i];
37+
i++;
38+
k++;
39+
}
40+
else{
41+
res[k]=nums2[j];
42+
j++;
43+
k++;
44+
}
45+
}
46+
while(i<m){
47+
res[k]=nums1[i];
48+
i++;
49+
k++;
50+
}
51+
while(j<n){
52+
res[k]=nums2[j];
53+
j++;
54+
k++;
55+
}
56+
if(res.length%2==0){
57+
return (double)(res[res.length/2]+res[res.length/2-1])/2;
58+
}
59+
return res[res.length/2];
60+
}
61+
}

0 commit comments

Comments
 (0)