[programmers] Lv3. 双優先級キューJavaScript|heap(hip)|protect-me


🕊 Link


Lv3. 2つの優先順位キューJavaScript
https://programmers.co.kr/learn/courses/30/lessons/42628

🧑🏻‍💻 Code(javascript)

function solution(os) {
  const l = os.length
  const q = []

  os.forEach(o => {
    const [text, number] = o.split(" ")

    if (text == "I") {
      q.push(+number)
    } else if (text == "D" && number == "1") {
      const max = Math.max(...q)
      const index = q.indexOf(max)
      q.splice(index, 1)
    } else if (text == "D" && number == "-1") {
      const min = Math.min(...q)
      const index = q.indexOf(min)
      q.splice(index, 1)
    }
  })

  if (!q.length) return [0, 0]
  const max = Math.max(...q)
  const min = Math.min(...q)
  return [max, min]
}

💡 Solution


最終コード(成功)-シン

function solution(os) {
  const l = os.length
  const q = []

  os.forEach(o => {
    const [text, number] = o.split(" ")
    if (text == "I") {
      q.push(+number)
    } else {
      const value = ((+number > 0) ? Math.max : Math.min)(...q) // ()() 이렇게 붙일 수 있음
      const index = q.indexOf(value)
      q.splice(index, 1)
    }
  })

  return q.length ? [Math.max(...q), Math.min(...q)] : [0, 0]
}

初期コード(成功)

// test code
const os = ["I -45", "I 653", "D 1", "I -642", "I 45", "I 97", "D 1", "D -1", "I 333"]
console.log(solution(os)); // [333, -45]

function solution(os) {
  const l = os.length
  const q = []

  os.forEach(o => { // os의 요소들을 돈다.
    // os의 요소 o를 공백 문자로 나누어 text와 number에 할당(구조분해할당)
    const [text, number] = o.split(" ")

    if (text == "I") {
      // text가 I인 경우, number를 q에 넣는데, `+기호`를 붙여 문자열이 아닌 숫자로 push
      q.push(+number) 
    } else if (text == "D" && number == "1") {
      // text가 D, number가 1인 경우
      // 최대값을 먼저 찾고
      const max = Math.max(...q)
      // 최대값의 index를 찾은 후
      const index = q.indexOf(max)
      // q에서 잘라내기
      q.splice(index, 1)
    } else if (text == "D" && number == "-1") {
      // max 값을 찾아 잘라낸 것과 마찬가지로 min 값도 찾아 잘라냄
      const min = Math.min(...q)
      const index = q.indexOf(min)
      q.splice(index, 1)
    }
  })

  if (!q.length) return [0, 0] // q가 비어있을 경우 [0, 0] 반환
  const max = Math.max(...q)
  const min = Math.min(...q)
  return [max, min] // 그렇지 않을 경우 최대값, 최소값 반환
}

👨🏻‍💻💭 Self Feedback

  • levelはなぜ3の問題なのか.
  • 22021.08.12-最初に作成された
  • 댓글 환영 질문 환영 by.protect-me