inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

파이썬 알고리즘 문제풀이 입문(코딩테스트 대비)

10. 최소힙

자바스크립트에서는 항상 맨날 힙 구현해서 풀어야했는데..

543

ncprog1

작성한 질문수 5

1

실시간 정렬해야되는 문제들 보면 거의 무조건 힙구조도 같이 이용해야하는 문제들이여서..

자바스크립트로 풀때는 최소 빨라도 3~4분정도는..

요로코롬

Min이나 Max 힙 구조 만드는데 소요해야하고,

class MaxHeap {
  constructor() {
    this.heap = [null];
  }

  push(value) {
    this.heap.push(value);
    let currentIndex = this.heap.length - 1;
    let parentIndex = Math.floor(currentIndex / 2);
    while (parentIndex !== 0 && value > this.heap[parentIndex]) {
      const temp = this.heap[parentIndex];
      this.heap[parentIndex] = value;
      this.heap[currentIndex] = temp;

      currentIndex = parentIndex;
      parentIndex = Math.floor(currentIndex / 2);
    }
  }

  pop() {
    if (this.heap.length === 1) return;
    if (this.heap.length === 2) {
      return this.heap.pop();
    }

    const returnValue = this.heap[1];

    this.heap[1] = this.heap.pop();
    let currentIndex = 1;
    let leftIndex = 2;
    let rightIndex = 3;

    while (
      this.heap[currentIndex] < this.heap[leftIndex] ||
      this.heap[currentIndex] < this.heap[rightIndex]
    ) {
      if (this.heap[leftIndex] < this.heap[rightIndex]) {
        const temp = this.heap[currentIndex];
        this.heap[currentIndex] = this.heap[rightIndex];
        this.heap[rightIndex] = temp;

        currentIndex = rightIndex;
      } else {
        const temp = this.heap[currentIndex];
        this.heap[currentIndex] = this.heap[leftIndex];
        this.heap[leftIndex] = temp;

        currentIndex = leftIndex;
      }

      leftIndex = currentIndex * 2;
      rightIndex = currentIndex * 2 + 1;
    }

    return returnValue;
  }
}

 

심지어 문제 구조에서, 힙에 들어가야하는게 객체요소이면서, 객체의 어떤 Key 값에 따라서 실시간 정렬해야할 경우엔 여기서 또 out of index , key값 더 생각해서,

 

class MinHeap {
  constructor() {
    this.heap = [null];
  }

  isEmpty() {
    return this.heap.length === 1;
  }

  _swap(a, b) {
    [this.heap[a], this.heap[b]] = [this.heap[b], this.heap[a]];
  }

  push(value) {
    this.heap.push(value);
    let currentIndex = this.heap.length - 1;
    let parentIndex = Math.floor(currentIndex / 2);

    //
    while (parentIndex !== 0 && this.heap[parentIndex].key > value.key) {
      this._swap(parentIndex, currentIndex);

      currentIndex = parentIndex;
      parentIndex = Math.floor(currentIndex / 2);
    }
  }

  pop() {
    if (this.isEmpty()) return;
    if (this.heap.length === 2) return this.heap.pop();

    const returnValue = this.heap[1];
    this.heap[1] = this.heap.pop();

    let currentIndex = 1;
    let leftIndex = 2;
    let rightIndex = 3;

    while (
      (this.heap[leftIndex] &&
        this.heap[currentIndex].key > this.heap[leftIndex].key) ||
      (this.heap[rightIndex] && this.heap[currentIndex].key > this.heap[rightIndex].key)
    ) {
      if (this.heap[rightIndex] === undefined) {
        this._swap(leftIndex, currentIndex);
        currentIndex = leftIndex;
      } else if (this.heap[rightIndex].key < this.heap[leftIndex].key) {
        this._swap(rightIndex, currentIndex);
        currentIndex = rightIndex;
      } else if (this.heap[rightIndex].key >= this.heap[leftIndex].key) {
        this._swap(leftIndex, currentIndex);
        currentIndex = leftIndex;
      }

      leftIndex = currentIndex * 2;
      rightIndex = currentIndex * 2 + 1;
    }

    return returnValue;
  }
}

 

요로코롬 이렇게 힙구조 작성하는데만 4~5분 먹고, 그담 문제 풀이 본격적으로 시작할 수 있습니다..

파이썬의 deque 같은경우는 자바스크립트에선 Queue 구조 1분. 먹고

왜 사람들이 파이썬 코테로 많이 쓰는지 알겠네요..

ㄷㄷ;;

import heapq , 단 1초면 모듈 가져오고, 끝이네요.

코테에서 import 모듈 제한 없다면 진짜 무조건 파이썬이네요 ;;

 

 

 

코테 준비 같이 해요! 코딩-테스트 python

답변 0

기존에 윈도우 10으로 잘 써왔는데 윈도우 11로 바꾸고 나서 채점이 안됩니다.

1

78

2

스택에서 ')'을 만나는 경우

0

80

3

문제가 어디있나요?

0

67

2

변수 or 함수명

0

62

1

침몰하는 타이타닉 문제 질문입니다

0

59

1

AA.py 책점 에러

0

60

1

오늘 구매했는데 파이썬 자료구조 궁금한거 있으면 답변이 잘 될까요.

0

111

2

5.동전분배하기 문제 밑에코드도 정답이될까요?

0

110

1

아나그램 비교 코드

0

116

2

AA.PY파일 복사 후 채점 진행할때 오류 발생합니다.

0

161

2

문제 링크가있나여?

0

147

2

채점기 Time Limit Exceeded 오류 문의

1

166

2

동적계획법은 사용하는 문제

0

126

2

제 코드 좀 봐주세요

0

148

1

예외가 존재할 가능성?

0

97

1

3번이 안풀립니다

0

95

0

5번 틀림

0

115

0

오류원인?

0

99

0

리스트 선언

0

108

1

침몰하는 타이타닉(그리디) 문제 질문

0

111

1

알고리즘

0

70

1

코딩테스트

0

93

1

DFS 순서 질문드립니다.

0

129

2

left, right를 사용한 풀이법에 대한 질문입니다

0

91

1