There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
nums1 = [1, 3] nums2 = [2] The median is 2.0 Example 2:
nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5
Solution 1:
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int totalLength = nums1.length+nums2.length;
int[] helper = new int[totalLength];
int count = 0;
int left = 0;
int right = 0;
while(left<nums1.length && right<nums2.length && count<=((totalLength/2)+1)){
if(nums1[left]<=nums2[right]){
helper[count] = nums1[left];
left++;
}else{
helper[count] = nums2[right];
right++;
}
count++;
}
while(count<=(totalLength/2)+1){
if(left<nums1.length){
helper[count] = nums1[left];
left++;
}else if(right<nums2.length){
helper[count] = nums2[right];
right++;
}
count++;
}
double median;
int mid = totalLength/2;
if(totalLength%2==0) {
//System.out.println(helper[mid-1]+" "+helper[mid]);
median = (double)(helper[mid-1]+helper[mid])/2;
}else{
median = (double)helper[mid];
}
return median;
}
} Question : Given an array of integers A, return the largest integer that only occurs once.…
Jump search algorithm is a pretty new algorithm to search for an element in a…
What is Knuth Morris Pratt or KMP algorithm ? KMP is an algorithm which is…
Binary Search is a Logarithmic search which finds the target element in a sorted array…
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X…
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such…
This website uses cookies.