본문 바로가기
IT/알고리즘

35★] Leetcode 1299. Replace Elements with Greatest Element on Right Side

by 깻잎쌈 2020. 7. 19.
반응형

 

 

Replace Elements with Greatest Element on Right Side - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

for문 두 번 돌려도 되지만 시간 초과.

대신 뒤에서부터 최댓값을 계산하면서 vector에는 앞에서부터 값을 추가해주면 된다.

class Solution {
public:
    vector<int> replaceElements(vector<int>& arr) {
        vector<int>ans;
        int max = 0;
        ans.insert(ans.begin(),-1);
        
        for(int i = arr.size()-1;i>0;i--){
            if(arr[i] > max)
               max = arr[i];
            
            ans.insert(ans.begin(),max);
        }
       
        return ans;
    }
};

 

push_back은 뒤에서 추가하는 거고

insert를 사용하면 앞에서 추가한다.

 

 

*참고*

 

Insert things in the beginning of a vect - C++ Forum

Hello. I am having trouble finding a good tutorial about how to insert a number in the beginning of a vector. Some say that I should use push_back(), however I it seems as the push_back function does something else. Like push it back to the back of the vec

www.cplusplus.com

 

 

반응형

댓글