Professional Documents
Culture Documents
Median of Two Sorted Array
Median of Two Sorted Array
brute force approach is that first merge two array through different forms then
sort that and find the median
here the twist is that adding array in the array and findingg the medianis
difficult part
take the array merge that first then do sorting if array islegth is odd then
median is middle value otherwise we have to add the n/2 and n+1/2
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
// here the arraycopy is the funcion is used for mergeing two array
// first the arraycopy working
// (object src , int postion_of_src , Object des , int postion_of_des , int
length of array till it will copy)
Arrays.sort(num3);
if(nums3.length / 2 != 0){
return l3+1/2;
}else {
double ex = (nums3.length / 2) + ((nums3.length/2)+1);
return ex/2;
}
}
}
class solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int len = nums1.length()+nums2.length();
int []merged = new int [len];
int i = 0;
int j = 0;
int k = 0;
if (merged.length % 2 == 1){
median = merged[mid];
}
else {
median = (merged[mid] + merged[mid-1])/2.0;
}
return 0;
}
}
*/
/*
The correct soultion is that first i have store the first using new merged array of
double
in that sort the array after taht to find the median we have to create the varaible
of median or in that
store that value if length is odd then it is middle value or in other case
*/
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
double[] arr=new double[nums1.length+nums2.length];
for(int i=0;i<arr.length;i++){
if(i<nums1.length){
arr[i]=nums1[i];
}else arr[i]=nums2[arr.length-i-1];
}
Arrays.sort(arr);
if(arr.length%2!=0){
return arr[arr.length/2];
}else return (arr[arr.length/2]+arr[(arr.length-1)/2])/2.0;
}
}