1. 题目一
给出题目一的试题链接如下:
1. 解题思路
这一题我实现的比较暴力,就是先找到最大最小值,然后顺序检索找出第一个不等于这两个值的数返回。
2. 代码实现
给出python代码实现如下:
class Solution:
def findNonMinOrMax(self, nums: List[int]) -> int:
_min = min(nums)
_max = max(nums)
for x in nums:
if x != _min and x != _max:
return x
return -1
提交代码评测得到:耗时381ms,占用内存16.4MB。
2. 题目二
给出题目二的试题链接如下:
1. 解题思路
这一题思路整体也还好,就是找到第一段不包含a
的最长连续子串,将其减一即可。
2. 代码实现
给出python代码实现如下:
class Solution:
def smallestString(self, s: str) -> str:
n = len(s)
idx = 0
l, r = -1, -1
while idx < n and s[idx] == "a":
idx += 1
l = idx
while idx < n and s[idx] != "a":
idx += 1
r = idx
if l == n:
return s[:-1] + "z"
def op(ch):
if ch == "a":
return "z"
return chr(ord(ch)-1)
sub = "".join(op(ch) for ch in s[l:r])
return s[:l] + sub + s[r:]
提交代码评测得到:耗时255ms,占用内存22.5MB。
3. 题目三
给出题目三的试题链接如下:
1. 解题思路
今天状态真的是不好,这道题把我卡了n久,简直了……
本质上来说,就是遍历一下最大移动距离为0到n-1的情况,然后对于任意最大移动距离为k的情况下,对于任意一个点所需的最小cost就是其本身到之前k个点当中最小值的大小,我们用一个动态规划即可快速得到。
综上,我们即可得到我们的最终答案。
2. 代码实现
给出python代码实现如下:
class Solution:
def minCost(self, nums: List[int], x: int) -> int:
n = len(nums)
dp = [[cost for cost in nums] for _ in range(n)]
for i in range(1, n):
for j in range(n):
dp[i][j] = min(dp[i-1][j], nums[(j-i+n) % n])
costs = [sum(s) + i * x for i, s in enumerate(dp)]
return min(costs)
提交代码评测得到:耗时5046ms,占用内存25.3MB。
4. 题目四
给出题目四的试题链接如下:
这道题我放弃了,实在是毫无思路……
如果有大佬知道怎么做的话请务必赐教一下,感激不尽!