개발이 취미인 주니어 기획자

[스택(Stack)][JavaScript][LeetCode] #735. Asteroid Collision 본문

문제 풀이/알고리즘 문제 풀이

[스택(Stack)][JavaScript][LeetCode] #735. Asteroid Collision

큐 2023. 4. 13. 10:30
728x90
반응형

#STACK  #스택  #MEDIUM 

 

Search Insert Position - LeetCode

Can you solve this real interview question? Search Insert Position - Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must w

leetcode.com

🌷 문제 설명

✏️ LeetCode 연습문제: Asteroid Collision
We are given an array asteroids of integers representing asteroids in a row.
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.

🎃 제한 사항
2 <= asteroids.length <= 10^4
-1000 <= asteroids[i] <= 1000
asteroids[i] != 0

입출력 예

asteroids result
[5, 10, -5] [5, 10]
[8, -8] []
[10, 2, -5]
[10]

 

🌷 내 코드

var asteroidCollision = function(asteroids) {
  let stack = []

  for (let i=0; i<asteroids.length; i++) {
      if (asteroids[i] > 0) {
          stack.push(asteroids[i])
      } else {
          while (stack.length > 0 
            && stack[stack.length-1]>0 
            && stack[stack.length-1] < Math.abs(asteroids[i])) {
              stack.pop()
          }

          if (stack[stack.length-1] > 0 && stack[stack.length-1] + asteroids[i] < 0 ) {
              stack.pop()
          } else if (stack[stack.length-1] + asteroids[i] === 0) {
              stack.pop()
              continue;
          } else if (stack[stack.length-1] + asteroids[i] > 0 ){
              continue
          }
          stack.push(asteroids[i])
      }
  }
  return stack
};

 

🌷 코멘트

이거슨.. 내가 오늘(04/12) 풀었던 코테문제를 다시 풀어봄.. Accepted 떴을 때 이렇게까지 반가웠던건 싸피에서 삼성 IM 받았을 때 이후로 처음이었다. 정확히 이렇게 풀었는진 모르는데 대애충 저런 느낌으로 풀었다. 크게 다르지 않을 듯. 사실 오늘 못 푼 문제 중 linked list문제 어제 풀까말까 한 문제 나왔는데 너무 속상했다.. 보통 dfs 나올 확률이 더 높으니까 dfs를 풀었는데 진짜 진짜 너무 아쉬웠다 엉어ㅓ엉엉 ... 암튼 감독해주시는 분이 너무 친절하게 말씀해주셔서 좋았다.  제가 다음엔 더 잘해져서 나타나겠읍니다,, 서류를 붙여준거 하나로만으로도 너무 감사했다. 저에게 시간을 투자해주셔서 감사하구,, 제송함다,,ㅠ 수싫문 개발블로그 2년차 여전히 문송할뿐,, 

Algorithm streak 은 어떤 알고리즘을 활용하는지 확실히 정해져있어서, 처음 접근할 때 고민할 거리가 썩 없었는데, 이렇게 문제만 주니 어떤 알고리즘을 써야 할지 뇌정지가 오긴 하더라. 첨엔 투포인터로 해보려고 했다가 머리에서 각이 안서서 어제 푼 dfs 문제 생각나서 stack써봤다(흐름이 좀 이상하긴한뎈ㅋㅋㅋㅋ?ㅋ?ㅋ몇 개 없는 아는 알고리즘 돌려쓰기). 

블로그 내용에 문제가 있다면 댓글 혹은 아래로 연락주세요!

~대가리 꽃밭인 디지털 노마드가 꿈이예요~

🧚‍♀️ Gyumin Lee

📧 gyumin.q.lee@gmail.com

 

qminlee723 - Overview

noob. qminlee723 has 8 repositories available. Follow their code on GitHub.

github.com

728x90
반응형