-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfindMedianSortedArrays.py
98 lines (97 loc) · 2.77 KB
/
findMedianSortedArrays.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
class Solution:
# @param {integer[]} nums1
# @param {integer[]} nums2
# @return {float}
def findMedianSortedArrays(self, nums1, nums2):
m,n = len(nums1),len(nums2)
if m == 0 and n == 0:
return 0
elif m == 0 :
mid = n/2
if n%2: #odd
return nums2[mid]
else:
return (nums2[mid-1]+nums2[mid])/2.0
elif n == 0:
mid = m/2
if m%2: #odd
return nums1[mid]
else:
return (nums1[mid-1]+nums1[mid])/2.0
mid = (m+n)/2
p1 = 0
p2 = 0
while(p1<=mid and p2 < n):
if p1 >=len(nums1):
nums1.append(nums2[p2])
p2+=1
p1+=1
else:
if nums2[p2]<=nums1[p1]:
nums1.insert(p1,nums2[p2])
p2+=1
p1+=1
else:
p1+=1
if (m+n)%2: # odd
return nums1[mid]
else: #even
return (nums1[mid-1]+nums1[mid])/2.0
# @param {integer[]} nums1
# @param {integer[]} nums2
# @return {float}
def findMedianSortedArrays2(self, nums1, nums2):
m,n = len(nums1),len(nums2)
if m == 0 and n == 0:
return 0
elif m == 0 :
mid = n/2
if n%2: #odd
return nums2[mid]
else:
return (nums2[mid-1]+nums2[mid])/2.0
elif n == 0:
mid = m/2
if m%2: #odd
return nums1[mid]
else:
return (nums1[mid-1]+nums1[mid])/2.0
mid = (m+n)/2
p2 = 0
p1 = 0
while(p1<=mid and p2 < n):
target = nums2[p2]
if p1 >= len(nums1):
nums1 += nums2[p2:]
break
else:
idx = self.bsindex(nums1[p1:],target)
p1 = p1 + idx
if p1 >= len(nums1):
nums1+=nums2[p2:]
break
else:
nums1.insert(p1, target)
p2 += 1
p1 += 1
if (m+n)%2: # odd
return nums1[mid]
else: #even
return (nums1[mid-1]+nums1[mid])/2.0
def bsindex(self, nums,target):
n = len(nums)
low = 0
high = n-1
while(low<=high):
if target <=nums[low]:
return low
if target >= nums[high]:
return high + 1
mid = (low+high)/2
if nums[mid] == target:
return mid + 1
elif nums[mid]>target:
high = mid-1
else:
low = mid + 1
return low