LeetCode1299. Replace Elements with Greatest Element on Right Side(Easy)

給一個aray,請你將每個元素用它右邊最大的元素替換,如果是最後一個元素,用-1替換。

Input: arr = [17,18,5,4,6,1]
Output: [18,6,6,6,1,-1]
Explanation: 
- index 0 --> the greatest element to the right of index 0 is index 1 (18).
- index 1 --> the greatest element to the right of index 1 is index 4 (6).
- index 2 --> the greatest element to the right of index 2 is index 4 (6).
- index 3 --> the greatest element to the right of index 3 is index 4 (6).
- index 4 --> the greatest element to the right of index 4 is index 5 (1).
- index 5 --> there are no elements to the right of index 5, so we put -1.


ans1.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
public:
    vector<int> replaceElements(vector<int>& arr) {
        int curMax = 0, tmp;       
        for(int i = arr.size() - 1; i >= 0; i--){
            tmp = arr[i];
            if(i == arr.size() - 1){
                arr[i] = -1;
            }else{
                arr[i] = curMax;
            }
            curMax = max(curMax, tmp);
        }
        
        return arr;
    }
};







Ref:
https://blog.51cto.com/u_15739363/5764533
https://cdn.acwing.com/solution/content/7294/
https://github.com/keineahnung2345/leetcode-cpp-practices/blob/master/1299.%20Replace%20Elements%20with%20Greatest%20Element%20on%20Right%20Side.cpp

留言

這個網誌中的熱門文章

何謂淨重(Net Weight)、皮重(Tare Weight)與毛重(Gross Weight)

Architecture(架構) 和 Framework(框架) 有何不同?_軟體設計前的事前規劃的藍圖概念

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題