Problem Solving/LeetCode
2023.09.21 Today's Challenge
fabichoi
2023. 9. 21. 23:45
https://leetcode.com/problems/median-of-two-sorted-arrays/
LeetCode - The World's Leading Online Programming Learning Platform
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
이진탐색의 변형 문제.
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
if len(nums1) > len(nums2):
return self.findMedianSortedArrays(nums2, nums1)
m, n = len(nums1), len(nums2)
left, right = 0, m
while left <= right:
partitionA = (left + right) // 2
partitionB = (m + n + 1) // 2 - partitionA
maxLeftA = float('-inf') if partitionA == 0 else nums1[partitionA - 1]
minRightA = float('inf') if partitionA == m else nums1[partitionA]
maxLeftB = float('-inf') if partitionB == 0 else nums2[partitionB - 1]
minRightB = float('inf') if partitionB == n else nums2[partitionB]
if maxLeftA <= minRightB and maxLeftB <= minRightA:
if (m + n) % 2 == 0:
return (max(maxLeftA, maxLeftB) + min(minRightA, minRightB)) / 2
else:
return max(maxLeftA, maxLeftB)
elif maxLeftA > minRightB:
right = partitionA - 1
else:
left = partitionA + 1
반응형