1299. Replace Elements with Greatest Element on Right Side

Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1.

After doing so, return the array.

n2做法 两层for循环去找到i后面所有的j的max值

n的做法,维护一个从右往左的max值就行

class Solution(object):
    def replaceElements(self, arr):
        """
        :type arr: List[int]
        :rtype: List[int]
        """
        right_max = [0] * len(arr)
        right_max[-1] = arr[-1]
        for i in range(len(arr) - 2, -1, -1):
            right_max[i] = max(right_max[i + 1], arr[i])
        ans = [-1] * len(arr)
        for i in range(0, len(arr) - 1, 1):
            ans[i] = right_max[i + 1]
        return ans
        
原文地址:https://www.cnblogs.com/whatyouthink/p/13207274.html