얼렁뚱땅 스며드는 Data Science

Algorithm/Daily Coding Tests Challenge

[Leetcode] Hard : Median of Two Sorted Array

Jesip14 2021. 10. 9. 16:09

Description

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)).

 

My Solution

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        new_list = []
        i, j = 0, 0
        while(i < len(nums1) and j < len(nums2)):
            if nums1[i] <= nums2[j]:
                new_list.append(nums1[i])
                i += 1
            else:
                new_list.append(nums2[j])
                j += 1
        

        if i != len(nums1) :
            for k in range(i, len(nums1)):
                new_list.append(nums1[k])
        elif j != len(nums2):
            for k in range(j, len(nums2)):
                new_list.append(nums2[k])
        
        return new_list[len(new_list) // 2] if len(new_list) % 2 == 1 else (new_list[(len(new_list) // 2) - 1] + new_list[len(new_list) // 2]) / 2

 

문제출처 : 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