Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

/*

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 i have to use the double not int

int num3[] = new int[nums1.length + nums2.length];

// 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)

System.arraycopy(nums1 , 0 , nums3 , 0 , nums1.length);

// here the num3 starting destion is from l1


System.arraycopy(nums2 , 0 , nums3 , nums1.length , nums2.length);

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;

while(i < nums1.length && j < nums2.length){


if (nusm1[i] < nusm2[j]){
merged [k] = nusm1[i];
i++;
k++;
}else {
meregd [k] = nusm2 [j];
j++;
k++;
}
}

while (i < nums.length){


merged [k] = nusm1[i];
i++;
k++;
}

while (j < nusm2.length){


meregd [k] = nusm2 [j];
j++;
k++;
}
double median = 0.0;
int mid = merged.length/2;

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

8 => as per the formula for even


4 + 3 / 2.0 => 4

*/

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;
}
}

You might also like