1299. Each element with the largest element on the right side

https://leetcode-cn.com/problems/replace-elements-with-greatest-element-on-right-side/

To give you an array arr, you replace each element with the largest element to its right, if it is the last element, replace it with -1.

After all replacement operation, please return this array.

 

Example:

Input: arr = [17,18,5,4,6,1]
Output: [18,6,6,6,1, -1]
 

prompt:

1 <= arr.length <= 10^4
1 <= arr[i] <= 10^5

Reverse traversal, with the greatest attention is the replacement of the right elements, excluding itself

class Solution {
public:
    vector<int> replaceElements(vector<int>& arr) {
        int len = arr.size();
        int maxn = arr[len - 1];
        arr[len - 1] = -1;
        for(int i = (len - 2); i >= 0; --i)
        {
            int tmp = maxn;
            maxn = max(maxn, arr[i]);
            arr[i] = tmp;
        }
        return arr;
    }
};

 

Published 84 original articles · won praise 7 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_43569916/article/details/104216249