algorithm

735. Asteroid Collision

식피두 2020. 10. 18. 21:47

https://leetcode.com/problems/asteroid-collision/

 

Asteroid Collision - 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

스택 문제를 더 연습하고 싶어서 하나 더 골라봤다.

 

고려해야할 경우의 수를 잘 나눠놓고 접근해야 무한루프에 빠지지 않는다.

 

스택을 이용하되, 연쇄작용 하는 부분을 신경써야함.

 

40% 

class Solution:
    def asteroidCollision(self, asteroids: List[int]) -> List[int]:
        stack = []
        
        for cur in asteroids:
            if not stack:
                stack.append(cur)
                continue
            
            while stack:
                # +5, -5
                eq_diff_sign = abs(cur) == abs(stack[-1]) and cur != stack[-1] and stack[-1] > cur
                if eq_diff_sign:
                    stack.pop()
                    break
                
                # +5, +8 or -5 -7
                same_sign = (cur/abs(cur)) == (stack[-1]/abs(stack[-1]))
                if same_sign:
                    stack.append(cur)
                    break
                
                # +5, -9 or -5, +9
                collide = stack[-1] > cur
                if collide:
                    if abs(stack[-1]) < abs(cur):
                        stack.pop()
                        if stack:
                            continue
                        else:
                            stack.append(cur)
                            break
                    else:
                        break
                else:
                    stack.append(cur)
                    break
            
        return stack

 

99%

와 뭐야...

조건을 정리하는 부분이 매우 깔끔..

while else 구문 및...

파이썬에서 가능한 a < b < c 문법을 사용함으로써 매우 간결하게 정리했다..ㅜㅜ 

class Solution:
    def asteroidCollision(self, asteroids: List[int]) -> List[int]:
        if not asteroids or len(asteroids) == 1:
            return asteroids
        
        stack = []
        
        for incoming in asteroids:
            while stack and incoming < 0 < stack[-1]:
                if -incoming == stack[-1]:
                    stack.pop()
                    break
                elif -incoming < stack[-1]:
                    break
                else:
                    stack.pop()
            else:
                stack.append(incoming)
                
        return stack

'algorithm' 카테고리의 다른 글

496. Next Greater Element I  (0) 2020.10.20
1544. Make The String Great  (0) 2020.10.18
316. Remove Duplicate Letters [R]  (0) 2020.10.18
1405. Longest Happy String  (0) 2020.09.14
638. Shopping Offers  (0) 2020.09.12