Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
LeetCode/median-of-two-sorted-arrays
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
50 lines (42 sloc)
1.32 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
There are two sorted arrays nums1 and nums2 of size m and n respectively. | |
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). | |
You may assume nums1 and nums2 cannot be both empty. | |
Example 1: | |
nums1 = [1, 3] | |
nums2 = [2] | |
The median is 2.0 | |
Example 2: | |
nums1 = [1, 2] | |
nums2 = [3, 4] | |
The median is (2 + 3)/2 = 2.5 | |
My code: | |
class Solution: | |
def findMedianSortedArrays(self, nums1, nums2): | |
""" | |
:type nums1: List[int] | |
:type nums2: List[int] | |
:rtype: float | |
""" | |
result=[] | |
length=len(nums1)+len(nums2) | |
i=0 | |
j=0 | |
while i+j<length: | |
if i==len(nums1) and j!=len(nums2): | |
result.append(nums2[j]) | |
j+=1 | |
elif j==len(nums2) and i!=len(nums1): | |
result.append(nums1[i]) | |
i+=1 | |
elif nums1[i]<nums2[j]: | |
result.append(nums1[i]) | |
i+=1 | |
else: | |
result.append(nums2[j]) | |
j+=1 | |
if length%2==1 and i+j==int(length/2)+1: | |
return float(result[-1]) | |
elif length%2==0 and i+j==int(length/2)+1: | |
return float((result[-1]+result[-2])/2) | |
Solution: | |
https://leetcode.com/problems/median-of-two-sorted-arrays/ |