classSolution(object): deffindMedianSortedArrays(self, nums1, nums2): m, n = len(nums1), len(nums2) if m > n: return self.findMedianSortedArrays(nums2, nums1)
start, end = 0, m k = (m + n) // 2 while start <= end: cut1 = start + (end - start) // 2 cut2 = k - cut1 # Deal with edge case 1 : length l1 = nums1[cut1-1] if cut1 > 0else -float('inf') l2 = nums2[cut2-1] if cut2 > 0else -float('inf') r1 = nums1[cut1] if cut1 < m else float('inf') r2 = nums2[cut2] if cut2 < n else float('inf') if l1 > r2: end = cut1 - 1 elif l2 > r1: start = cut1 + 1 else: # Deal with the edge case 2 : odd or even! if (m+n) % 2: return min(r1, r2) else: return (max(l1,l2) + min(r1,r2)) / 2.0
Division simply requires us to find how many times we can subtract the divisor from the the dividend without making the dividend negative
i 1, 2, 4, 8, 16, 32, 64 …
i 1, 2, 4, 8, …
i …
i 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Same Thought classSolution(object): defdivide(self, dividend, divisor): np = (dividend < 0) ^ (divisor < 0) dividend = abs(dividend) divisor = abs(divisor) res = 0 while dividend >= divisor: tmp, i = divisor, 1 while dividend >= tmp: dividend -= tmp res += i i = i << 1 tmp = tmp << 1 if np: res = -res return min(max(-2147483648, res), 2147483647)
clean
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution(object): defdivide(self, dividend, divisor): sign = (dividend > 0) ^ (divisor > 0) dividend, divisor = abs(dividend), abs(divisor) res = 0 i = 1 div = divisor while dividend >= div: dividend -= div res += i i = i << 1 div = div << 1 if dividend < div: # when div bigger enough that dividend can not minus it i = 1 div = divisor
if sign: res = -res return min(max(-2147483648, res), 2147483647)
classSolution(object): deffindClosestElements(self, arr, k, x): if x <= arr[0]: return arr[:k] elif x >= arr[-1]: return arr[-k:] else: index = bisect.bisect_left(arr, x) left = max(0, index-k) right = min(len(arr)-1, index+k-1) while right - left > k-1: if arr[right] - x >= x - arr[left]: right -= 1 else: left += 1 return arr[left:right+1]