-
Notifications
You must be signed in to change notification settings - Fork 64
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
fb0ec05
commit c8e465b
Showing
1 changed file
with
32 additions
and
17 deletions.
There are no files selected for viewing
49 changes: 32 additions & 17 deletions
49
Hard/4. Median of Two Sorted Arrays/New approach[Arraylist]/Solution.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | ||
} | ||
} | ||
} | ||
} |