[leetcode] 1299. Replace Elements with Greatest Element on Right Side

网友投稿 569 2022-10-01

[leetcode] 1299. Replace Elements with Greatest Element on Right Side

[leetcode] 1299. Replace Elements with Greatest Element on Right Side

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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:微信小程序实现签到的日历功能(微信小程序签到怎么自动签到)
下一篇:mybatis中&lt;choose&gt;标签的用法说明
相关文章

 发表评论

暂时没有评论,来抢沙发吧~