|
| 1 | +''' |
| 2 | +There are two sorted arrays A and B of size m and n respectively. |
| 3 | +
|
| 4 | +Find the median of the two sorted arrays. |
| 5 | +
|
| 6 | +The overall run time complexity should be O(log (m+n)). |
| 7 | +''' |
| 8 | + |
| 9 | +class Solution: |
| 10 | + # get media of A --> ma |
| 11 | + # get count of number in B that smaller than ma |
| 12 | + def getNumBiggerThanValue(self, Array, Value): |
| 13 | + # lower bounder is better |
| 14 | + for i in range(len(Array)): |
| 15 | + if Array[i] > Value: |
| 16 | + return i + 1 |
| 17 | + return len(Array) |
| 18 | + |
| 19 | + # return iA, iB |
| 20 | + def moveFoward(self, A, B, iA, iB): |
| 21 | + # min of A[iA + 1], B[iB] |
| 22 | + if iB == len(B): |
| 23 | + return iA + 1, iB |
| 24 | + elif iA == len(A): |
| 25 | + return iB + 1, iA |
| 26 | + else |
| 27 | + |
| 28 | + # @return a float |
| 29 | + def findMedianSortedArrays(self, A, B): |
| 30 | + lenA = len(A) |
| 31 | + lenB = len(B) |
| 32 | + mid = (lenA + lenB) / 2 |
| 33 | + if lenA >= lenB: |
| 34 | + iA = len(A) / 2 |
| 35 | + iB = self.getNumBiggerThanValue(B, A[iA]) |
| 36 | + else: |
| 37 | + iB = len(B) / 2 |
| 38 | + iA = self.getNumBiggerThanValue(A, B[iB]) |
| 39 | + A.append(0x8ffffffff) |
| 40 | + B.append(0x8ffffffff) |
| 41 | + |
| 42 | + while True: |
| 43 | + ## step |
| 44 | + left = iA + iB |
| 45 | + #print mid, left, iA, iB, ".." |
| 46 | + if left == mid: |
| 47 | + return min(A[iA], B[iB]) |
| 48 | + elif left < mid: |
| 49 | + # step forward |
| 50 | + if A[iA - 1] > B[iB - 1]: |
| 51 | + iB+=1 |
| 52 | + else: |
| 53 | + iA+=1 |
| 54 | + elif left > mid: |
| 55 | + # step backward |
| 56 | + if A[iA] > B[iB]: |
| 57 | + iA-=1 |
| 58 | + else: |
| 59 | + iB-=1 |
| 60 | + #print "A:%d, B:%d" %(A[iA], B[iB]) |
| 61 | + |
| 62 | + |
| 63 | +if __name__ == '__main__': |
| 64 | + slu = Solution() |
| 65 | + print slu.findMedianSortedArrays([1], [2]) |
| 66 | + print slu.findMedianSortedArrays([1, 12, 15, 26, 38], [2, 13, 17, 30, 45, 50]) |
| 67 | + print slu.findMedianSortedArrays([1, 12, 15, 26, 38], [2, 13, 17, 30, 45]) |
| 68 | + print slu.findMedianSortedArrays([1, 2, 5, 6, 8], [13, 17, 30, 45, 50]) |
| 69 | + print slu.findMedianSortedArrays([1, 2, 5, 6, 8, 9, 10], [13, 17, 30, 45, 50]) |
| 70 | + print slu.findMedianSortedArrays([1, 2, 5, 6, 8, 9], [13, 17, 30, 45, 50]) |
| 71 | + print slu.findMedianSortedArrays([1, 2, 5, 6, 8], [11, 13, 17, 30, 45, 50]) |
| 72 | + print slu.findMedianSortedArrays([1], [2,3,4]) |
| 73 | + ## [1,2,3] --> 2 |
| 74 | + ## [1,2,3,4] --> 3 |
| 75 | + ## [1,2,4,5,5,8] ==> 5 |
| 76 | + ## [1,2,4,5,5,6,8] ==> 5 |
| 77 | + |
| 78 | + |
| 79 | + |
| 80 | + |
0 commit comments