알고리즘

[LeetCode] Median of Two Sorted Arrays

개발정리 2021. 6. 17. 22:06

 

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        if (nums1.length == 0 && nums2.length == 0) return 0;    
        
        int[] mergeArr = new int[nums1.length + nums2.length];
        
        for(int i=0; i<mergeArr.length; i++) {
            if(i<nums1.length) {
                mergeArr[i] = nums1[i];
                continue;
            }
            mergeArr[i] = nums2[mergeArr.length-i-1];
        }
        
        Arrays.sort(mergeArr);
        
        int index = mergeArr.length/2;
        
        if(mergeArr.length % 2==0) {    
            return Double.valueOf(mergeArr[index-1] + mergeArr[index]) / 2;
        } else {
            return Double.valueOf(mergeArr[index]);
        }
    }
}

[사이트]

https://leetcode.com/problems/median-of-two-sorted-arrays/

 

Median of Two Sorted Arrays - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

[해설 블로그]

https://engkimbs.tistory.com/623

 

[LeetCode, 리트코드] Median of Two Sorted Arrays

1. Problem 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 as..

engkimbs.tistory.com