๋ฌธ์
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 |