【leetcode】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.
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
解题思路:从右往左遍历arr,同时记录出现的最大值即可。
代码如下:
class Solution(object): def replaceElements(self, arr): """ :type arr: List[int] :rtype: List[int] """ res = [-1] max_val = arr[-1] for i in range(len(arr)-2,-1,-1): res.insert(0,max_val) max_val = max(arr[i], max_val) return res
相关推荐
满地星辰 2020-09-16
shqhope 2020-06-23
WebVincent 2020-06-16
lynjay 2020-06-14
ajaxtony 2020-06-11
有梦就能实现 2020-06-05
zhendeshifeng 2020-05-27
gcgl000hugang 2020-02-10
Yasin 2020-05-05
Darklovy 2020-04-16
hellobabygogo 2020-03-06
程松 2020-02-23
wbingyang 2020-02-16
文山羊 2020-02-14
zehuawong 2020-02-11
jiahaohappy 2020-01-10