Skip to content

Commit

Permalink
[python]median-of-two-sorted-arrays 2
Browse files Browse the repository at this point in the history
  • Loading branch information
Huauauaa committed Aug 18, 2024
1 parent 2fa5a98 commit f4c5e48
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 21 deletions.
9 changes: 9 additions & 0 deletions src/leetcode/00004.median-of-two-sorted-arrays/4.md
Original file line number Diff line number Diff line change
@@ -1 +1,10 @@
# [4. 寻找两个正序数组的中位数](https://leetcode.cn/problems/median-of-two-sorted-arrays/)

## 中位数

```python
def mean(nums):
nums.sort()
mid = len(nums) // 2
return (nums[mid] + nums[~mid]) / 2
```
55 changes: 34 additions & 21 deletions src/leetcode/00004.median-of-two-sorted-arrays/4.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,42 @@
from typing import List


# class Solution:
# def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
# res = nums1[::]

# def inset(t):
# left = 0
# right = len(res) - 1
# while left <= right:
# mid = (left + right) >> 1
# if res[mid] > t:
# right = mid - 1
# else:
# left = mid + 1
# res.insert(left, t)

# for i in nums2:
# inset(i)


# length = len(res)
# if length % 2 == 0:
# return (res[length // 2 - 1] + res[length // 2]) / 2
# else:
# return res[length // 2]
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
res = nums1[::]

def inset(t):
left = 0
right = len(res) - 1
while left <= right:
mid = (left + right) >> 1
if res[mid] > t:
right = mid - 1
else:
left = mid + 1
res.insert(left, t)

for i in nums2:
inset(i)

length = len(res)
if length % 2 == 0:
return (res[length // 2 - 1] + res[length // 2]) / 2
else:
return res[length // 2]
res = []
while nums1 and nums2:
if nums1[0] >= nums2[0]:
res.append(nums2.pop(0))
else:
res.append(nums1.pop(0))
res += nums1 + nums2

mid = len(res) // 2
return (res[mid] + res[~mid]) / 2


if __name__ == "__main__":
Expand Down

0 comments on commit f4c5e48

Please sign in to comment.