[LeetCode] 622. Design Circular Queue, Medium

2025. 4. 1. 16:17·CodingTest/LeetCode
반응형

1. 문제

  • 요구사항에 맞는 Circular Queue를 구현하라

2. 해결

class MyCircularQueue {
    queue: Array<number|null>;
    front: number;
    rear: number;
    
    constructor(k: number) {
        this.queue = new Array(k+1).fill(null);        
        this.front = 0;
        this.rear = 0;
    }

    enQueue(value: number): boolean {
        if(this.isFull()) return false;
        
        this.queue[this.rear] = value;
        this.rear = (this.rear+1) % this.queue.length;
        return true;
    }

    deQueue(): boolean {
        if(this.isEmpty()) return false;
        
        this.queue[this.front] = null;
        this.front = (this.front+1) % this.queue.length;

        return true;
    }   

    Front(): number {
        const front = this.queue[this.front];
        return front !== null ? front : -1; 
    }

    Rear(): number {
        const rear = this.queue[(this.rear-1 + this.queue.length) % this.queue.length];
        return rear !== null ? rear : -1; 
    }

    isEmpty(): boolean {
        return this.rear === this.front
    }

    isFull(): boolean {
        return (this.rear + 1) % this.queue.length === this.front
    }
}

/**
 * Your MyCircularQueue object will be instantiated and called as such:
 * var obj = new MyCircularQueue(k)
 * var param_1 = obj.enQueue(value)
 * var param_2 = obj.deQueue()
 * var param_3 = obj.Front()
 * var param_4 = obj.Rear()
 * var param_5 = obj.isEmpty()
 * var param_6 = obj.isFull()
 */
  • 처음에 딱 맞는 사이즈로 큐를 만들었는데, 이렇게 만들면 rear, front가 둘 다 0인 경우 비어있거나 꽉 차있는 경우가 동시에 존재할 수 있다.
  • 그렇기 때문에 추가 공간을 하나 만들어서, full과 empty를 구별해야 한다.
  • Rear 함수 부분도 0번 인덱스인 경우 -1을 참조할 수 있으므로 조심해야 한다.
저작자표시 (새창열림)
'CodingTest/LeetCode' 카테고리의 다른 글
  • [LeetCode] 752. Open the Lock, Medium
  • [LeetCode] 200. Number of Islands, Medium
  • [LeetCode] 61. Rotate List, Medium
  • [LeetCode] 138. Copy List with Random Pointer, Medium
뜸부깅
뜸부깅
코딩에 대한 여러 개인적인 생각을 정리하고 공부를 하는 공간입니다!!
  • 뜸부깅
    코오오딩
    뜸부깅
  • 전체
    오늘
    어제
    • Note (429)
      • Skill (31)
        • Java & Spring (9)
        • Javascript & HTML & CSS (0)
        • React (0)
        • Next.js (22)
      • CodingTest (389)
        • 백준 온라인 저지(BOJ) (140)
        • 프로그래머스(Programmers) (79)
        • LeetCode (170)
      • Algorithm & Data Structure (6)
      • [Project] 포트폴리오 (3)
        • Front end (3)
        • Back end (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    TypeScript
    boj2108
    BOJ
    meidum
    Easy
    component-scan
    프로그래머스
    백준2751
    백준7576
    boj1427
    Java
    백준
    백준1260
    백준7576자바
    next 14
    자바
    알고리즘
    백준1427
    leetcode 2236
    medium
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
뜸부깅
[LeetCode] 622. Design Circular Queue, Medium
상단으로

티스토리툴바