1. 题目一
给出题目一的试题链接如下:
1. 解题思路
这一题就是翻译一下题目就行,倒是没啥需要多说的……
2. 代码实现
给出python代码实现如下:
class Solution:
def isWinner(self, player1: List[int], player2: List[int]) -> int:
def get_score(player):
score, rep = 0, 1
for i, s in enumerate(player):
score += s * rep
if s == 10 or (i >= 1 and player[i-1]==10):
rep = 2
else:
rep = 1
return score
s1, s2 = get_score(player1), get_score(player2)
if s1 > s2:
return 1
elif s1 < s2:
return 2
else:
return 0
提交代码评测得到:耗时266ms,占用内存16.3MB。
2. 题目二
给出题目二的试题链接如下:
1. 解题思路
这一题我们的思路同样比较直接,就是遍历一下每一行和每一列,看看它们分别在什么时候可以涂满。
而任意一行或者一列被涂满的时间就是其上的所有格子中最后一个被涂的格子的时间,这是很快就能得到的。
2. 代码实现
给出python代码实现如下:
class Solution:
def firstCompleteIndex(self, arr: List[int], mat: List[List[int]]) -> int:
n, m = len(mat), len(mat[0])
index = {x: i for i, x in enumerate(arr)}
row = min(max(index[mat[i][j]] for j in range(m)) for i in range(n))
col = min(max(index[mat[i][j]] for i in range(n)) for j in range(m))
return min(row, col)
提交代码评测得到:耗时1245ms,占用内存51.7MB。
3. 题目三
给出题目三的试题链接如下:
1. 解题思路
这一题我们的思路就是一个剪枝的dfs算法。
我们每次考察从当前走到跳跃点或者终点的情况,然后将其按照cost分别加入到队列当中,然后每次都pop出cost最小的路线考察下一步,直到有某一条路线走到了终点即可。
2. 代码实现
给出pyton代码实现如下:
class Solution:
def minimumCost(self, start: List[int], target: List[int], specialRoads: List[List[int]]) -> int:
def get_cost(start, target):
return abs(start[0]-target[0]) + abs(start[1]-target[1])
start, target = tuple(start), tuple(target)
specialRoads = [((x[0], x[1]), (x[2], x[3]), x[4]) for x in specialRoads]
q = [(0, start)]
seen = set()
while q:
cost, pos = heapq.heappop(q)
if pos == target:
return cost
if pos in seen:
continue
seen.add(pos)
for st, ed, _cost in specialRoads:
if ed in seen:
continue
heapq.heappush(q, (cost + get_cost(pos, st) + _cost, ed))
heapq.heappush(q, (cost + get_cost(pos, target), target))
return -1
提交代码评测得到:耗时169ms,占用内存17.8MB。
4. 题目四
给出题目四的试题链接如下:
1. 解题思路
这一题说来有点惭愧,一开始居然没有做出来,因为被要求不存在回文这个条件给搞懵了,因此完全没有想到任何思路。
后来看了大佬们的答案之后才惊觉,不存在任何回文子串事实上只要某个位置上的字符不与前一个字符或者再前一个字符相同即可,此时就必然不存在任何子串包含回文……
因此,我们只需要求一下字符序下下一个满足条件的字符串即可,而这个我们通过调整法即可得到。
2. 代码实现
给出python代码实现如下:
class Solution:
def smallestBeautifulString(self, s: str, k: int) -> str:
chars = [ord(ch) - ord('a') for ch in s]
n = len(chars)
idx = n-1
chars[idx] += 1
while 0 <= idx < n:
if chars[idx] >= k:
while idx >= 0 and chars[idx] >= k:
chars[idx] = 0
idx -= 1
if idx >= 0:
chars[idx] += 1
else:
while (idx-1 >= 0 and chars[idx-1] == chars[idx]) or (idx-2 >= 0 and chars[idx-2] == chars[idx]):
chars[idx] += 1
if chars[idx] < k:
idx += 1
if idx == -1:
return ""
chars = [chr(x + ord('a')) for x in chars]
return "".join(chars)
提交代码评测得到:耗时754ms,占用内存19.1MB。