'''
Description: 5963. 反转两次的数字
Autor: 365JHWZGo
Date: 2021-12-26 10:33:25
LastEditors: 365JHWZGo
LastEditTime: 2021-12-26 10:36:27
Author: localhost
'''
class Solution(object):
def isSameAfterReversals(self, num):
"""
:type num: int
:rtype: bool
"""
if num == 0:
return True
l = list(str(num))
if int(l[-1]) == 0:
return False
else:
return True
'''
Description: 5964. 执行所有后缀指令
Autor: 365JHWZGo
Date: 2021-12-26 10:42:03
LastEditors: 365JHWZGo
LastEditTime: 2021-12-26 14:05:10
Author: localhost
'''
class Solution(object):
def executeInstructions(self, n, startPos, s):
"""
:type n: int
:type startPos: List[int]
:type s: str
:rtype: List[int]
"""
x,y = startPos
res = []
for i in range(len(s)):
step = 0
for j in range(i,len(s)):
if s[j] == 'R':
y = y+1
elif s[j] == 'L':
y = y-1
elif s[j] == 'U':
x = x-1
else:
x = x+1
if x>=n or y>=n or x<0 or y <0:
break
else:
step +=1
res.append(step)
x,y = startPos
print(res)
return res
'''
Description: 5965. 相同元素的间隔之和
Autor: 365JHWZGo
Date: 2021-12-26 10:42:03
LastEditors: 365JHWZGo
LastEditTime: 2021-12-26 14:02:10
Author: localhost
'''
class Solution(object):
def getDistances(self, arr):
"""
:type arr: List[int]
:rtype: List[int]
"""
res = [0 for _ in range(len(arr))]
dp = [[] for _ in range(100000)]
# print(dp)
#将所有相同的元素的下标放在一起
for i in range(len(arr)):
dp[arr[i]-1].append(i)
l = list(set(arr))
for i in l:
#resf,前缀和,resb,后缀和
resf,resb = 0,0
#计算前缀和
for j in range(1, len(dp[i-1])):
resf = resf+(dp[i-1][j]-dp[i-1][j-1])*j
res[dp[i-1][j]] += resf
#计算后缀和
for j in range(len(dp[i-1])-2,-1,-1):
resb = resb+(dp[i-1][j+1]-dp[i-1][j])*(len(dp[i-1])-1-j)
res[dp[i-1][j]] += resb
return res
前两道题不难,第三道题也不难,但是有时间限制,你必须要降低复杂度才可以
一开始我写的是
class Solution(object):
def getDistances(self, arr):
"""
:type arr: List[int]
:rtype: List[int]
"""
dp = [[0 for _ in range(len(arr))]for _ in range(len(arr))]
for i in range(len(arr)):
for j in range(i+1,len(arr)):
if arr[i] == arr[j]:
dp[i][i]+=j-i
dp[j][j]+=j-i
res = [dp[i][i] for i in range(len(arr))]
return res
其实就是依次遍历相加距离,奈何超时间了
后来又进行了改进相当于我只遍历当前为arr[i]的那些元素所在下标,奈何题目就偏要让我再降复杂度~
class Solution(object):
def getDistances(self, arr):
"""
:type arr: List[int]
:rtype: List[int]
"""
res = [0 for _ in range(len(arr))]
dp = [[] for _ in range(100000)]
# print(dp)
for i in range(len(arr)):
dp[arr[i]-1].append(i)
l = list(set(arr))
for i in l:
for j in range(len(dp[i-1])-1):
for k in range(j+1,len(dp[i-1])):
res[dp[i-1][j]] += dp[i-1][k]-dp[i-1][j]
res[dp[i-1][k]] += dp[i-1][k]-dp[i-1][j]
return res
再接再厉!下周争取多做出一道题。