-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMedianOf2SortedArrays.java
More file actions
61 lines (61 loc) · 1.62 KB
/
MedianOf2SortedArrays.java
File metadata and controls
61 lines (61 loc) · 1.62 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class Solution {
// A bette rapproach for median in two sorted arrays Striver Sheet
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int index1Element=-1;
int index2Element=-1;
int n=nums1.length+nums2.length;
int index1=n/2-1;
int index2=n/2;
int count=0;
int i=0;
int j=0;
while(i<nums1.length && j<nums2.length){
if(nums1[i]<nums2[j]){
if(count==index1){
index1Element=nums1[i];
}
if(count==index2){
index2Element=nums1[i];
}
count++;
i++;
}
else{
if(count==index1){
index1Element=nums2[j];
}
if(count==index2){
index2Element=nums2[j];
}
count++;
j++;
}
}
while(i<nums1.length){
if(count==index1){
index1Element=nums1[i];
}
if(count==index2){
index2Element=nums1[i];
}
count++;
i++;
}
while(j<nums2.length){
if(count==index1){
index1Element=nums2[j];
}
if(count==index2){
index2Element=nums2[j];
}
count++;
j++;
}
if(n%2!=0){
return (double)index2Element;
}
else{
return ((double)index1Element + (double)index2Element)/2;
}
}
}