文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
Replace Elements with Greatest Element on Right Side
2. Solution
解析:Version 1,先排序获取索引,从最大值所在的索引开始遍历,只要是其左侧没有更新过的值都更新,使用left
来确定范围,left
始终是已更新数据的最右侧,其是下一次遍历的左边界。Version 2从倒数第二个元素开始向前遍历,maximum
用来保存右侧最大值,每次遍历先更新当前索引结果位置的数值为maximum
,然后更新maximum
。
- Version 1
class Solution:
def replaceElements(self, arr: List[int]) -> List[int]:
n = len(arr)
result = [-1] * n
indexes = sorted(range(n), key=lambda i: arr[i], reverse=True)
left = 0
for i in range(n):
index = indexes[i]
for j in range(left, index):
result[j] = arr[index]
left = max(left, index)
return result
- Version 2
class Solution:
def replaceElements(self, arr: List[int]) -> List[int]:
n = len(arr)
result = [-1] * n
maximum = arr[-1]
i = n - 2
while i > -1:
result[i] = maximum
maximum = max(maximum, arr[i])
i -= 1
return result