๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm/Leetcode

[Leetcode] Last Stone Weight (#1046)

 

 

๋ฌธ์ œ 

 

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 together. Suppose the heaviest two stones have weights x and y with x <= y. The result of this smash is:

  • If x == y, both stones are destroyed, and
  • If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x.

At the end of the game, there is at most one stone left.

Return the smallest possible weight of the left stone. If there are no stones left, return 0.

 

 

์ž…์ถœ๋ ฅ 
Input: stones = [2,7,4,1,8,1]
Output: 1
Explanation: 
We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,
we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,
we combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone.

 

 

ํ•ด์„ค ์ฝ”๋“œ 
class Solution(object):
    def lastStoneWeight(self, stones):
        stones.sort(reverse=True)
        
        while (len(stones) > 1):
            # ๋ฐฐ์—ด ๋‚ด ๊ฐ€์žฅ ํฐ ์ˆ˜์™€ ๋‘ ๋ฒˆ์งธ๋กœ ํฐ ์ˆ˜๋Š” ๊ณ„์† ์—†์•ค๋‹ค
            heaviest = max(stones)
            stones.remove(heaviest)
            heavier = max(stones)
            stones.remove(heavier)
            # ๋‘ ์ˆ˜๊ฐ€ ๋‹ค๋ฅผ ๋•Œ๋งŒ ๋‘ ์ˆ˜์˜ ์ฐจ๋ฅผ append ํ•ด์ค€๋‹ค
            if heaviest != heavier:
                stones.append(heaviest - heavier)
        if len(stones) == 0:
            return 0
        else:
            return stones[0]
๋ถ„์„ > ๋ฌธ์ œ์˜ ์›๋ฆฌ๋Š” ๊ฐ„๋‹จํ•˜๋‹ค. ๋ฐฐ์—ด์˜ ๊ธธ์ด๊ฐ€ 1 ๋ณด๋‹ค ํด ๋•Œ๊นŒ์ง€ ๋ฐฐ์—ด ๋‚ด ๊ฐ€์žฅ ํฐ ์ˆ˜์™€ ๋‘ ๋ฒˆ์งธ๋กœ ํฐ ์ˆ˜๋ฅผ ์—†์• ๊ณ  ๋‘ ์ˆ˜๊ฐ€ ๋‹ค๋ฅผ ๋•Œ๋งŒ ๋‘ ์ˆ˜์˜ ์ฐจ๋ฅผ appendํ•ด์ค€๋‹ค. ๋งˆ์ง€๋ง‰์œผ๋กœ ๋ฐฐ์—ด์˜ ๊ธธ์ด๊ฐ€ 0์ด ๋œ๋‹ค๋ฉด 0์„ ๋ฐ˜ํ™˜ํ•˜๊ณ  ๋‚˜๋จธ์ง€๋Š” ๋ฐฐ์—ด ๋‚ด์— ๋‚จ์•„์žˆ๋Š” ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๋ฉด ๋œ๋‹ค. 

 

 

๊ณ ์ฐฐ 
์ด ๋ฌธ์ œ๋ฅผ ํ’€ ๋•Œ ์ƒ๊ฐ๋ณด๋‹ค ๋‚œํ•ญ์„ ๊ฒช์—ˆ๋Š”๋ฐ, ๊ทธ ์ด์œ ๋Š” ๋ฌธ์ œ์˜ ์ง„ํ–‰ ์‚ฌํ•ญ์„ ์˜ˆ์‹œ๋Œ€๋กœ ์ •ํ™•ํ•˜๊ฒŒ ํ‘œํ˜„ํ•˜๋Š” ๋ฐ์—๋งŒ ์ง‘์ค‘ํ–ˆ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ๊ทธ๋Ÿฌ๋‹ค ๋ณด๋‹ˆ ์ค‘๊ฐ„์— ์ฝ”๋“œ๊ฐ€ ์ž์ฃผ ๊ผฌ์˜€๋‹ค. ์ด๋Ÿฌํ•œ ๊ณผ์ •์„ ๊ฒช์œผ๋ฉด์„œ ๋ฌธ์ œ๋ฅผ ํ’€ ๋•Œ ์ค‘์š”ํ•œ ๋ถ€๋ถ„์€ ๋ฌธ์ œ๋ฅผ ์–ด๋–ป๊ฒŒ ๋‹จ์ˆœํ•œ ์›๋ฆฌ๋กœ ์น˜ํ™˜ํ•˜๋Š” ๊ฒƒ์ด๋ผ๋Š” ์ƒ๊ฐ์ด ๋“ค์—ˆ๋‹ค. 

'Algorithm > Leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Leetcode] Print Words Vertically (#1324)  (0) 2022.04.20
[Leetcode] Reshape the Matrix (#566)  (0) 2022.04.20
[Leetcode] Complex Number Multiplication (#537)  (0) 2022.04.20
[Leetcode] Game of Life (#289)  (0) 2022.04.19
[Leetcode] Transpose Matrix (#867)  (0) 2022.04.18