본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 1046. Last Stone Weight

반응형

https://leetcode.com/problems/last-stone-weight/description/

 

Last Stone Weight - LeetCode

Can you solve this real interview question? Last Stone Weight - You are given an array of integers stones where stones[i] is the weight of the ith stone. We are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them

leetcode.com

simulation 문제였습니다.

📕 풀이방법

📔 풀이과정

stones의 size가 2이상인 동안 while loop를 수행하며 1. stones를 내림차순으로 정렬 후 가장 무거운 stones[0], stones[1] 원소 두 개를 부딛혀 쪼개줍니다. 사라진 돌은 무게가 0이 됩니다.2. stones의 원소 중 0인 것들을 제거해줍니다.

📔 정답 출력 | 반환

빈 경우 0을 아니라면 첫 번째 돌 무게를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    int lastStoneWeight(vector<int>& stones) {
        while(stones.size() >= 2) {
            sort(stones.rbegin(), stones.rend());

            if (stones[0] >= stones[1]) {
                stones[0] -= stones[1];
                stones[1] = 0;
            }
            stones.erase(remove(stones.begin(), stones.end(), 0), stones.end());
        }
        
        if(stones.empty()) return 0;
        return stones[0];
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.