第十一周算法作业 No.240 347 374
No.240 搜索二维矩阵 II
- 思路
从左下角开始搜索,只能往上边或者往右边移动
如果比当前值更小,往上移动
如果比当前值更大,往右移动
- 代码
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
height = len(matrix)
width = len(matrix[0])
# 从左下角开始搜索
row = height-1
col = 0
while row>=0 and col<width:
# 只能往上边或者往右边移动
if target==matrix[row][col]:
return True
# 如果比当前值更小,往上移动
# 如果比当前值大,往右移动
if target<matrix[row][col]:
row = row-1
elif target>matrix[row][col]:
col = col+1
return False
- 作业截图
No.347 前 K 个高频元素
- 思路
使用python的库collections统计各个数字的出现频率
然后使用优先队列库heapq来获取前k个出现频率最高的元素
- 代码
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
count = collections.Counter(nums)
heap = [(val, key) for key, val in count.items()]
return [item[1] for item in heapq.nlargest(k, heap)]
- 作业截图
No.374 猜数字大小
- 思路
采用二分查找,如果:
pick < num,修改上限
pick > num,修改下限
直到找到为止
- 代码
class Solution(object):
def guessNumber(self, n):
"""
:type n: int
:rtype: int
"""
down = 1
up = n
num = (up-down)//2 + down
# 采用二分查找
while guess(num)!=0:
#print(down,up,num)
if guess(num)==-1:
# pick < num,修改上限
up = num-1
else:
# pick > num,修改下限
down = num+1
num = (up-down)//2 + down
return num
- 作业截图