สมมติว่าเรามีอาร์เรย์ A เราต้องแทนที่ทุกองค์ประกอบด้วยองค์ประกอบที่ยิ่งใหญ่ที่สุดทางด้านขวาขององค์ประกอบนี้ และแทนที่อันสุดท้ายด้วย -1 ดังนั้น ถ้า A =[5, 17, 40, 6, 3, 8, 2] ก็จะเป็น [40,40,8,8,8,8,2,-1]
เพื่อแก้ปัญหานี้ เราจะทำตามขั้นตอนเหล่านี้ -
- เราจะอ่านองค์ประกอบอาร์เรย์จากขวาไปซ้าย
- เอา :=-1
- สำหรับ i :=n – 1 ถึง 0
- อุณหภูมิ :=อี
- e :=max ระหว่าง e และ array[i]
- array[i] :=อุณหภูมิ
- อาร์เรย์ส่งคืน
ตัวอย่าง
ให้เราดูการใช้งานต่อไปนี้เพื่อความเข้าใจที่ดีขึ้น -
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<int> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
class Solution {
public:
vector<int> replaceElements(vector<int>& arr) {
int rep = -1;
int n = arr.size();
for(int i = n - 1; i >= 0; i--){
int temp = rep;
rep = max(rep, arr[i]);
arr[i] = temp;
}
return arr;
}
};
main(){
Solution ob;
vector<int> c = {5,17,40,6,3,8,2};
print_vector(ob.replaceElements(c)) ;
} อินพุต
[5,17,40,6,3,8,2]
ผลลัพธ์
[40,40,8,8,8,2,-1]