LeetCode 4. Median of Two Sorted Arrays in Python

차민재·2022년 2월 25일
0
post-thumbnail

문제

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.

두 배열의 합에서 중앙값 구하기.

풀이

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        #중앙값 문제
        for i in nums2:
            nums1.append(i)
        
        arr = sorted(nums1)
        mindex = 0
        if len(arr) %2 == 1:
            mindex = (len(arr)-1)/2
            answer = arr[mindex]
        else:
            mindex =  (len(arr)-1)/2
            answer = (float)(arr[mindex] + arr[mindex+1])/2
        
        return answer

과정

문제 그대로 배열을 합해주고, 배열의 길이가 짝수,홀수일 때를 나눠서 리턴한다.

느낀 점

문자열 다루는 것도 파이썬을 이용해서 많이 풀어봐야겠다.

profile
안녕하세요

0개의 댓글