본문 바로가기
LeetCode

[LeetCode] 4. Median of Two Sorted Arrays

by JungSeung 2023. 10. 11.
728x90

https://leetcode.com/

Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

The overall run time complexity should be O(log (m+n)).

Example 1:

Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.

 

Example 2:

Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.

 
Constraints:

  • nums1.length == m
  • nums2.length == n
  • 0 <= m <= 1000
  • 0 <= n <= 1000
  • 1 <= m + n <= 2000
  • -10^6 <= nums1[i], nums2[i] <= 10^6

 

Solutions Code :

var findMedianSortedArrays = function(nums1, nums2) {
    let n1 = nums1.length;
    let n2 = nums2.length;
    // 만약 nums1이 nums2보다 길다면 두 배열을 교환하여 nums1이 더 짧도록 만듭니다.
    if (n1 > n2) {
        return findMedianSortedArrays(nums2, nums1);
    }
    let l = 0;
    let r = n1;
    // 이진 검색을 수행합니다.
    while (l <= r) {
        let mid1 = Math.floor((l + r) / 2);
        let mid2 = Math.floor((n1 + n2 + 1) / 2 - mid1);
        // 각 배열의 왼쪽과 오른쪽의 요소들을 찾습니다.
        let maxLeft1 = (mid1 == 0) ? Number.MIN_SAFE_INTEGER : nums1[mid1 - 1];
        let minRight1 = (mid1 == n1) ? Number.MAX_SAFE_INTEGER : nums1[mid1];

        let maxLeft2 = (mid2 == 0) ? Number.MIN_SAFE_INTEGER : nums2[mid2 - 1];
        let minRight2 = (mid2 == n2) ? Number.MAX_SAFE_INTEGER : nums2[mid2];
        // 조건을 확인하여 중앙값을 찾습니다.
        if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) {
            if ((n1 + n2) % 2 == 0) {
                return (Math.max(maxLeft1, maxLeft2) + Math.min(minRight1, minRight2)) / 2;
            } else {
                return Math.max(maxLeft1, maxLeft2);
            }
        } else if (maxLeft1 > minRight2) {
            r = mid1 - 1;
        } else {
            l = mid1 + 1;
        }
    }
    // 중앙값을 찾지 못한 경우 -1을 반환합니다.
    return -1;
};

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

 

728x90

'LeetCode' 카테고리의 다른 글

[LeetCode] 7. Reverse Integer  (0) 2023.10.16
[LeetCode] 6. Zigzag Conversion  (0) 2023.10.13
[LeetCode] 3. Longest Substring Without Repeating Characters  (0) 2023.10.11
[LeetCode] 2. Add Two Numbers  (0) 2023.10.11
[LeetCode] 1. Two Sum  (2) 2023.10.10