Skip to content

Commit 88eef57

Browse files
authored
Create find-kth-largest-xor-coordinate-value.py
1 parent 681bfc0 commit 88eef57

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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

Comments
 (0)