zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    cull/clip distance example
    Sutherland-Hodgeman多边形裁剪
    OpenCV 脸部跟踪(3)
    人脸识别中的Procruster analysis应用
    卡尔曼滤波的原理说明
    偏导数
    泊松分布E(X^2)
    抽奖概率
    卡尔曼滤波的原理说明
    卡尔曼滤波3
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/13207832.html
Copyright © 2011-2022 走看看