Data Structures & Algorithms

Leetcode 4 Median of Two Sorted Arrays Java Solution

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

Recent Posts

Largest Unique Number Java Solution

Question : Given an array of integers A, return the largest integer that only occurs once.…

10 months ago

Jump Search Algorithm In Java

Jump search algorithm is a pretty new algorithm to search for an element in a…

1 year ago

Knuth Morris Pratt Pattern Search Algorithm

What is Knuth Morris Pratt or KMP algorithm ? KMP is an algorithm which is…

1 year ago

Binary Search Algorithm In Java

Binary Search is a Logarithmic search which finds the target element in a sorted array…

1 year ago

Leetcode Integer to Roman Java Solution

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X…

2 years ago

Leetcode Container With Most Water Java Solution

Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such…

2 years ago

This website uses cookies.