Skip to content

Commit

Permalink
fix: Java Solution for Problem 4
Browse files Browse the repository at this point in the history
  • Loading branch information
godkingjay authored Oct 16, 2023
1 parent fb0ec05 commit c8e465b
Showing 1 changed file with 32 additions and 17 deletions.
Original file line number Diff line number Diff line change
@@ -1,27 +1,42 @@
import java.util.ArrayList;
public class Solution{
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
ArrayList<Integer> list = new ArrayList<>(); //ArrayList Initialization

//Add Elements from `nums1` to `list`
for(int i:nums1){
list.add(i);
}
//Add Elements from `nums2` to `list`
for(int j:nums2){
list.add(j);
}
int a = nums1.length;
int b = nums2.length;

double sum=0; //Initialize a Sum Variable
// Calculate the total length of the merged array
int c = a + b;

for(int i=0;i<list.size();i++){
sum += list.get(i); //Calculate the Sum of Elements
// Create a new integer array to hold the merged elements
int[] arr = new int[c];

// Copy elements from nums1 into arr
for (int i = 0; i < a; i++) {
arr[i] = nums1[i];
}

double res = sum/list.size(); //Calculate the Average (Mean)

return res; //Return the Median Value
// Copy elements from nums2 into arr, starting from position a
for (int i = 0; i < b; i++) {
arr[a + i] = nums2[i];
}

// Sort the merged array in ascending order
Arrays.sort(arr);

// Check if the length of the merged array is even or odd
if (c % 2 == 0) {
// Calculate the indices of the two middle elements
int mid1 = (c - 1) / 2;
int mid2 = mid1 + 1;

// Calculate the median as the average of the two middle elements
return (double) (arr[mid1] + arr[mid2]) / 2;
} else {
// Calculate the index of the middle element
int mid = (c - 1) / 2;

// Return the middle element as the median
return arr[mid];
}
}
}
}

0 comments on commit c8e465b

Please sign in to comment.