-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathMedianOfTwoSortedArrays.java
More file actions
41 lines (35 loc) · 951 Bytes
/
MedianOfTwoSortedArrays.java
File metadata and controls
41 lines (35 loc) · 951 Bytes
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
//JAVA code to get median of two sorted Arrays..
class Median {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
double[] arr = new double[nums1.length + nums2.length];
int i=0;
int j=0;
int k=0;
while(i < nums1.length && j < nums2.length){
if(nums1[i] < nums2[j]){
arr[k] = nums1[i];
i++;
}else{
arr[k] = nums2[j];
j++;
}
k++;
}
while(i < nums1.length){
arr[k] = nums1[i];
i++;
k++;
}
while(j < nums2.length){
arr[k] = nums2[j];
j++;
k++;
}
int mid = arr.length / 2;
if(arr.length % 2 == 1){
return arr[mid];
}else{
return (arr[mid] + arr[mid-1]) / 2;
}
}
}