|
| 1 | +# Time: O(m * n) on average |
| 2 | +# Space: O(m * n) |
| 3 | + |
| 4 | +import random |
| 5 | + |
| 6 | + |
| 7 | +class Solution(object): |
| 8 | + def kthLargestValue(self, matrix, k): |
| 9 | + """ |
| 10 | + :type matrix: List[List[int]] |
| 11 | + :type k: int |
| 12 | + :rtype: int |
| 13 | + """ |
| 14 | + def nth_element(nums, n, compare=lambda a, b: a < b): |
| 15 | + def tri_partition(nums, left, right, target, compare): |
| 16 | + mid = left |
| 17 | + while mid <= right: |
| 18 | + if nums[mid] == target: |
| 19 | + mid += 1 |
| 20 | + elif compare(nums[mid], target): |
| 21 | + nums[left], nums[mid] = nums[mid], nums[left] |
| 22 | + left += 1 |
| 23 | + mid += 1 |
| 24 | + else: |
| 25 | + nums[mid], nums[right] = nums[right], nums[mid] |
| 26 | + right -= 1 |
| 27 | + return left, right |
| 28 | + |
| 29 | + left, right = 0, len(nums)-1 |
| 30 | + while left <= right: |
| 31 | + pivot_idx = random.randint(left, right) |
| 32 | + pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare) |
| 33 | + if pivot_left <= n <= pivot_right: |
| 34 | + return |
| 35 | + elif pivot_left > n: |
| 36 | + right = pivot_left-1 |
| 37 | + else: # pivot_right < n. |
| 38 | + left = pivot_right+1 |
| 39 | + |
| 40 | + |
| 41 | + vals = [] |
| 42 | + for r in xrange(len(matrix)): |
| 43 | + curr = 0 |
| 44 | + for c in xrange(len(matrix[0])): |
| 45 | + curr = curr^matrix[r][c] |
| 46 | + if r == 0: |
| 47 | + matrix[r][c] = curr |
| 48 | + else: |
| 49 | + matrix[r][c] = curr^matrix[r-1][c] |
| 50 | + vals.append(matrix[r][c]) |
| 51 | + nth_element(vals, k-1, compare=lambda a, b: a > b) |
| 52 | + return vals[k-1] |
0 commit comments