LeetCode #1299. Replace Elements with Greatest Element on Right Side

题目

1299. Replace Elements with Greatest Element on Right Side


解题方法

设置maxnum = -1,从最后一位开始向前遍历数组,把arr[i]赋值成maxnum,maxnum取arr[i]中原来存放的值和maxnum的最大值,循环直到开头结束。
时间复杂度:O(n)
空间复杂度:O(1)


代码

class Solution:
    def replaceElements(self, arr: List[int]) -> List[int]:
        maxnum = -1
        for i in range(len(arr) - 1, -1, -1):
            arr[i], maxnum = maxnum, max(maxnum, arr[i])
        return arr
posted @ 2020-11-25 13:28  老鼠司令  阅读(53)  评论(0)    收藏  举报