Description
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.
Example 1:
Input: arr = [17,18,5,4,6,1]
Output: [18,6,6,6,1,-1]
Constraints:
- 1 <= arr.length <= 10^4.
- 1 <= arr[i] <= 10^5.
分析
题目的意思是:对于每个位置,找出其右边最大的值来替换当前的位置,最后一个位置设置为-1,这里从前往后暴力破解的话,肯定超时,于是从后往前来遍历就能够解决了哈。注意max_val要在从右向左遍历的时候更新
代码
class Solution:
def replaceElements(self, arr: List[int]) -> List[int]:
n=len(arr)
for i in range(n-1,-1,-1):
if(i==n-1):
max_val=arr[i]
arr[i]=-1
elif(max_val<arr[i]):
arr[i],max_val=max_val,arr[i]
else:
arr[i]=max_val
return arr