Skip to content

Commit 1922639

Browse files
Added Solution of Median of Two Sorted Array(Letcode) in Java.
1 parent abcff23 commit 1922639

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
3+
List<Integer> merged = new ArrayList<Integer>();
4+
for (int i= 0 ; i < nums1.length; i++){
5+
merged.add(nums1[i]);
6+
}
7+
for (int i = 0 ; i < nums2.length;i++){
8+
merged.add(nums2[i]);
9+
}
10+
Collections.sort(merged);
11+
int idx = merged.size()/2;
12+
if (merged.size()%2 != 0){
13+
return merged.get(idx);
14+
}
15+
return (merged.get(idx-1)+merged.get(idx))/2.0;
16+
17+
}
18+
}
19+
20+
// Example Test case
21+
//
22+
// Input: nums1 = [1,3], nums2 = [2]
23+
// Output: 2.00000
24+
// Explanation: merged array = [1,2,3] and median is 2.
25+
//
26+
//
27+
// Input: nums1 = [1,2], nums2 = [3,4]
28+
// Output: 2.50000
29+
// Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.

0 commit comments

Comments
 (0)