一.问题描述
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[i]来说,右边的最大值就是原arr[i+1]的值和现在arr[i+1]中的最大值。
如果用新开的一个数组来存结果而不改变arr的值,那就是rst[i+1]和arr[i+1]中的最大值。
给出两种实现。
时间复杂度:O(N)
更多leetcode算法题解法: 专栏 leetcode算法从零到结束 或者 leetcode 解题目录 Python3 一步一步持续更新~
三.源码
# version 1, extra array O(N) space
class Solution:
def replaceElements(self, arr: List[int]) -> List[int]:
rst=[-1]*len(arr)
for i in range(len(arr)-2,-1,-1):
rst[i]=arr[i+1] if arr[i+1]>rst[i+1] else rst[i+1]
return rst
# version 2, O(1) space
class Solution:
def replaceElements(self, arr: List[int]) -> List[int]:
temp=-1
for i in range(len(arr)-2,-1,-1):
if temp>arr[i+1]:arr[i],temp=temp,arr[i]
else:arr[i],temp=arr[i+1],arr[i]
arr[-1]=-1
return arr
# version 3: from leetcode demo
class Solution:
def replaceElements(self, arr: List[int]) -> List[int]:
if not arr:
return
max_ = -1
for i in range(len(arr)-1,-1,-1):
temp = arr[i]
arr[i] = max_
if temp > max_:
max_ = temp
return arr