-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMedianOfTwoSortedArrays.java
More file actions
49 lines (42 loc) · 1.08 KB
/
Copy pathMedianOfTwoSortedArrays.java
File metadata and controls
49 lines (42 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package LeetcodePractice;
public class MedianOfTwoSortedArrays {
public static double findMedianSortedArrays(int[] nums1, int[] nums2){
int m = nums1.length;
int n = nums2.length;
int[] mergedArray = new int[m+n];
int i=0;
int j=0;
int k=0;
while (i<m && j<n) {
if(nums1[i] < nums2[j])
{
mergedArray[k++] = nums1[i++];
}
else
{
mergedArray[k++] = nums2[j++];
}
}
while(i<m)
{
mergedArray[k++] =nums1[i++];
}
while (j<n)
{
mergedArray[k++] = nums2[j++];
}
int len =mergedArray.length;
if(len % 2 == 1)
{
return mergedArray[len/2];
}
else{
return (mergedArray[len/2 -1] + mergedArray[len/2]) /2.0;
}
}
public static void main(String[] args) {
int[] nums1 = {1,3};
int[] nums2 = {2};
System.out.println("Median: " + findMedianSortedArrays(nums1, nums2));
}
}