数据结构与算法之栈: LeetCode 641. 设计循环双端队列 (Ts版)

设计循环双端队列

描述

  • 设计实现双端队列。

  • 实现 MyCircularDeque 类:

    • MyCircularDeque(int k) :构造函数,双端队列最大为 k 。
    • boolean insertFront():将一个元素添加到双端队列头部。 如果操作成功返回 true ,否则返回 false 。
    • boolean insertLast() :将一个元素添加到双端队列尾部。如果操作成功返回 true ,否则返回 false 。
    • boolean deleteFront() :从双端队列头部删除一个元素。 如果操作成功返回 true ,否则返回 false 。
    • boolean deleteLast() :从双端队列尾部删除一个元素。如果操作成功返回 true ,否则返回 false 。
    • int getFront() ):从双端队列头部获得一个元素。如果双端队列为空,返回 -1 。
    • int getRear() :获得双端队列的最后一个元素。 如果双端队列为空,返回 -1 。
    • boolean isEmpty() :若双端队列为空,则返回 true ,否则返回 false 。
    • boolean isFull() :若双端队列满了,则返回 true ,否则返回 false 。

示例 1:

输入
["MyCircularDeque", "insertLast", "insertLast", "insertFront", "insertFront", "getRear", "isFull", "deleteLast", "insertFront", "getFront"]
[[3], [1], [2], [3], [4], [], [], [], [4], []]
输出
[null, true, true, true, false, 2, true, true, true, 4]

解释

MyCircularDeque circularDeque = new MycircularDeque(3); // 设置容量大小为3
circularDeque.insertLast(1);			        // 返回 true
circularDeque.insertLast(2);			        // 返回 true
circularDeque.insertFront(3);			        // 返回 true
circularDeque.insertFront(4);			        // 已经满了,返回 false
circularDeque.getRear();  				// 返回 2
circularDeque.isFull();				        // 返回 true
circularDeque.deleteLast();			        // 返回 true
circularDeque.insertFront(4);			        // 返回 true
circularDeque.getFront();				// 返回 4

提示:

  • 1 <= k <= 1000
  • 0 <= value <= 1000
  • insertFront, insertLast, deleteFront, deleteLast, getFront, getRear, isEmpty, isFull 调用次数不大于 2000 次

Typescript 版算法实现


1 ) 方案1:数组

class MyCircularDeque {
   
    private capacity: number;
    private rear: number;
    private front: number;
    private elements: number[];

    constructor(k: number) {
   
        this.capacity = k + 1; // 使用 k+1 来区分满和空的情况
        this.rear = 0;
        this.front = 0;
        this.elements = new Array<number>(this.capacity).fill(0);
    }

    insertFront(value: number): boolean {
   
        if (this.isFull()) {
   
            return false;
        }
        this.front = (this.front - 1 + this.capacity) % this.capacity;
        this.elements[this.front] = value;
        return true;
    }

    insertLast(value: number
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wang's Blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值