给出题目一的试题链接如下:
这一题的话只要对每一行做一个排序,然后取每一列的最大值相加即可。
给出python代码实现如下:
class Solution:
def deleteGreatestValue(self, grid: List[List[int]]) -> int:
n, m = len(grid), len(grid[0])
for i in range(n):
grid[i] = sorted(grid[i])
return sum(max(grid[i][j] for i in range(n)) for j in range(m))
提交代码评测得到:耗时187ms,占用内存18.4MB。
给出题目二的试题链接如下:
这一题我们只需要遍历一下每一个数作为起始点时其能够形成的平方数列的最大值即可。
给出python代码实现如下:
class Solution:
def longestSquareStreak(self, nums: List[int]) -> int:
nums = sorted(nums)
s = set(nums)
visited = set()
res = -1
for i in nums:
if i in visited:
continue
cnt = 1
visited.add(i)
while i*i in s:
i = i*i
visited.add(i)
cnt += 1
if cnt >= 2:
res = max(res, cnt)
return res
提交代码评测得到:耗时2888ms,占用内存34.1MB。
给出题目三的试题链接如下:
这一题倒是没啥好的思路,按照题意给出了一个最为暴力的解法,不过万幸没有超时,就先凑合用了……
给出python代码实现如下:
class Allocator:
def __init__(self, n: int):
self.mem = [0 for _ in range(n)]
def allocate(self, size: int, mID: int) -> int:
cnt = 0
for i, x in enumerate(self.mem):
if x == 0:
cnt += 1
else:
cnt = 0
if cnt == size:
for j in range(i-size+1, i+1):
self.mem[j] = mID
return i-size+1
return -1
def free(self, mID: int) -> int:
cnt = 0
for i, x in enumerate(self.mem):
if self.mem[i] == mID:
self.mem[i] = 0
cnt += 1
return cnt
提交代码评测得到:耗时6766ms,占用内存14.5MB。
给出题目四的试题链接如下:
这一题我的思路就是找到所有的临界漫溢情况,然后根据query去定位可以访问的格点的数目即可。
给出python代码实现如下:
class Solution:
def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]:
n, m = len(grid), len(grid[0])
seen = {(0, 0)}
q = [(grid[0][0], 0, 0)]
_max = grid[0][0]
ans = {}
cnt = 0
while q:
v, i, j = heapq.heappop(q)
cnt += 1
if v > _max:
_max = v
ans[_max] = cnt
if i-1 >= 0 and (i-1, j) not in seen:
heapq.heappush(q, (grid[i-1][j], i-1, j))
seen.add((i-1, j))
if i+1 < n and (i+1, j) not in seen:
heapq.heappush(q, (grid[i+1][j], i+1, j))
seen.add((i+1, j))
if j-1 >= 0 and (i, j-1) not in seen:
heapq.heappush(q, (grid[i][j-1], i, j-1))
seen.add((i, j-1))
if j+1 < m and (i, j+1) not in seen:
heapq.heappush(q, (grid[i][j+1], i, j+1))
seen.add((i, j+1))
ans = sorted(ans.items())
n = len(ans)
def query(q):
idx = bisect.bisect_left(ans, (q, 0))
if idx == 0:
return 0
else:
return ans[idx-1][1]
return [query(q) for q in queries]
提交代码评测得到:耗时2829ms,占用内存42.1MB。