Skip to content

Commit c94a204

Browse files
authored
Merge pull request #719 from rajeshkumar2024/median_of_two_sorted_array
Added Solution of Median of Two Sorted Array(Letcode) in Java.
2 parents 059b98b + e2f15f8 commit c94a204

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
3+
//Creating a ArrayList containing all the elements of both array
4+
List<Integer> merged = new ArrayList<Integer>();
5+
for (int i= 0 ; i < nums1.length; i++){
6+
merged.add(nums1[i]);
7+
}
8+
for (int i = 0 ; i < nums2.length;i++){
9+
merged.add(nums2[i]);
10+
}
11+
Collections.sort(merged);
12+
//Sorting the finally Merged Linked List
13+
int idx = merged.size()/2;
14+
//Finding the middle index to get the Median
15+
if (merged.size()%2 != 0){
16+
//If Size of arraylist is odd then the middle element will be the median of the ArrayList.
17+
return merged.get(idx);
18+
}
19+
20+
return (merged.get(idx-1)+merged.get(idx))/2.0;
21+
22+
}
23+
}
24+
25+
// Example Test case
26+
//
27+
// Input: nums1 = [1,3], nums2 = [2]
28+
// Output: 2.00000
29+
// Explanation: merged array = [1,2,3] and median is 2.
30+
//
31+
//
32+
// Input: nums1 = [1,2], nums2 = [3,4]
33+
// Output: 2.50000
34+
// Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.

0 commit comments

Comments
 (0)