1299. Replace Elements with Greatest Element on Right Side

问题:

替换当前元素为,当前元素以后元素的最大值。

最后一个元素替换为-1。

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

  

解法:

按照题意,要用右边的元素替换左边的元素。

即,左边元素的修改,要后于 右边元素。

因此从后往前 ← ,反向轮询。

同时,记录当前最大值,替换到下一个元素。

⚠️ 注意:由于会对当前元素赋值,因此在赋值前,记录当前元素为tmp,

赋值后,为下一个元素作准备,使用tmp,求当前最大值。

代码参考:

 1 class Solution {
 2 public:
 3     vector<int> replaceElements(vector<int>& arr) {
 4         int maxv=-1;
 5         for(int i=arr.size()-1; i>=0; i--){
 6             int tmp=arr[i];
 7             arr[i]=maxv;
 8             maxv=max(maxv, tmp);
 9         }
10         return arr;
11     }
12 };
原文地址:https://www.cnblogs.com/habibah-chang/p/13207832.html