378. 有序矩阵中第K小的元素(自己用暴力做的,二分查找有点没看懂)
class Solution(object):
def kthSmallest(self, matrix, k):
"""
二分法
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
h, w = len(matrix), len(matrix[0])
low, high = matrix[0][0], matrix[h-1][w-1]
while low <= high:
mid = (low + high) / 2
count = 0 #小于mid的数量
i = h - 1
j = 0
# 二分搜索
while i >= 0 and j < w:
if matrix[i][j] <= mid:
count += (i + 1)
j += 1
else:
i -= 1
if count >= k:
high = mid -1
else:
low = mid + 1
return low
class Solution(object):
def lastRemaining(self, n):
"""
:type n: int
:rtype: int
"""
c = 1
nums = [1,1,n]
while nums[2] > 1:
a,b,n = nums
if c&1:
nums = [a+b,b*2,n>>1]
else:
if nums[2] & 1:
nums = [a+b,b*2,n>>1]
else:
nums = [a,b*2,n>>1]
c += 1
return nums[0]