LeetCode 算法题库【641】——设计循环双端队列

设计循环双端队列

题目描述:

ti
mu

解题思路:

C#

  • 定义几个私有的量:队列,头尾指针,队列的长度和总长度。
  • 我们可以先写最后的IsEmptyIsFull函数,这两个就是判断是否为空和是否队列已满,只需要返回长度为0和长度为最大长度即可。
  • 中间的这些函数,每次都要判断是否为空和是否队列已满。
public class MyCircularDeque{
    private int[] _items;
    private int _lastIndex = -1;
    private int _frontIndex = -1;
    private int _size;
    private int _capacity;

    /** Initialize your data structure here. Set the size of the deque to be k. */
    public MyCircularDeque(int k){
        _items = new int[k];
        _capacity = k;
    }

    /** Adds an item at the front of Deque. Return true if the operation is successful. */
    public bool InsertFront(int value){
        if (!IsFull())
        {
            if (IsEmpty())
            {
                _frontIndex = 0;
                _lastIndex = 0;
            }
            else
            {
                if (_frontIndex == _capacity - 1)
                    _frontIndex = 0;
                else
                    _frontIndex++;
            }
            _items[_frontIndex] = value;
            _size++;
            return true;
        }
        else
            return false;
    }

    /** Adds an item at the rear of Deque. Return true if the operation is successful. */
    public bool InsertLast(int value){
        if (!IsFull())
        {
            if (IsEmpty())
            {
                _frontIndex = 0;
                _lastIndex = 0;
            }
            else
            {
                if (_lastIndex == 0)
                    _lastIndex = _capacity - 1;
                else
                    _lastIndex--;
            }
            _items[_lastIndex] = value;
            _size++;
            return true;
        }
        else
            return false;
    }

    /** Deletes an item from the front of Deque. Return true if the operation is successful. */
    public bool DeleteFront(){
        if (!IsEmpty())
        {
            if (_frontIndex == 0)
                _frontIndex = _capacity - 1;
            else
                _frontIndex--;
            _size--;
            if (_size == 0)
            {
                _lastIndex = -1;
                _frontIndex = -1;
            }
            return true;
        }
        else
            return false;
    }

    /** Deletes an item from the rear of Deque. Return true if the operation is successful. */
    public bool DeleteLast(){
        if (!IsEmpty())
        {
            if (_lastIndex == _capacity - 1)
                _lastIndex = 0;
            else
                _lastIndex++;
            _size--;
            if (_size == 0)
            {
                _lastIndex = -1;
                _frontIndex = -1;
            }
            return true;
        }
        else
            return false;
    }

    /** Get the front item from the deque. */
    public int GetFront(){
        if (!IsEmpty())
        {
            return _items[_frontIndex];
        }
        else
            return -1;
    }

        /** Get the last item from the deque. */
        public int GetRear()
        {
            if (!IsEmpty())
            {
                return _items[_lastIndex];
            }
            else
                return -1;
        }

    /** Checks whether the circular deque is empty or not. */
    public bool IsEmpty(){
        return _size == 0;
    }

    /** Checks whether the circular deque is full or not. */
    public bool IsFull(){
        return _size == _capacity;
    }
}

/**
 * Your MyCircularDeque object will be instantiated and called as such:
 * MyCircularDeque obj = new MyCircularDeque(k);
 * bool param_1 = obj.InsertFront(value);
 * bool param_2 = obj.InsertLast(value);
 * bool param_3 = obj.DeleteFront();
 * bool param_4 = obj.DeleteLast();
 * int param_5 = obj.GetFront();
 * int param_6 = obj.GetRear();
 * bool param_7 = obj.IsEmpty();
 * bool param_8 = obj.IsFull();
 */

1

python3

  • 定义队列、头尾指针和队列长度。
  • 插入队列头尾的函数要判断队列是否已满,而删除队列头尾的函数要判断队列是否为空。
class MyCircularDeque:
    items = []
    front = 0
    last = 0
    count = 0

    def __init__(self, k: int):
        """
        Initialize your data structure here. Set the size of the deque to be k.
        """
        self.items = [0 for _ in range(k)]

    def insertFront(self, value: int) -> bool:
        """
        Adds an item at the front of Deque. Return true if the operation is successful.
        """
        if self.isFull():
            return False
        if self.front == 0:
            self.front = len(self.items) - 1
        else:
            self.front -= 1
        # self.front = len(self.items) - 1 if self.front == 0 else self.front - 1
        self.items[self.front] = value
        self.count += 1
        return True

    def insertLast(self, value: int) -> bool:
        """
        Adds an item at the rear of Deque. Return true if the operation is successful.
        """
        if self.isFull():
            return False
        self.items[self.last] = value
        self.last = (self.last + 1) % len(self.items)
        self.count += 1
        return True

    def deleteFront(self) -> bool:
        """
        Deletes an item from the front of Deque. Return true if the operation is successful.
        """
        if self.isEmpty():
            return False
        self.front = (self.front + 1) % len(self.items)
        self.count -= 1
        return True

    def deleteLast(self) -> bool:
        """
        Deletes an item from the rear of Deque. Return true if the operation is successful.
        """
        if self.isEmpty():
            return False
        if self.last == 0:
            self.last = len(self.items) - 1
        else:
            self.last -= 1
        # self.last = len(self.items) - 1 if self.last == 0 else self.last - 1
        self.count -= 1
        return True

    def getFront(self) -> int:
        """
        Get the front item from the deque.
        """
        if self.isEmpty():
            return -1
        return self.items[self.front]

    def getRear(self) -> int:
        """
        Get the last item from the deque.
        """
        if self.isEmpty():
            return -1
        if self.last == 0:
            return self.items[len(self.items) - 1]
        else:
            return self.items[self.last - 1]
        # return self.items[len(self.items) - 1] if self.last == 0 else self.items[self.last - 1]

    def isEmpty(self) -> bool:
        """
        Checks whether the circular deque is empty or not.
        """
        return self.count == 0

    def isFull(self) -> bool:
        """
        Checks whether the circular deque is full or not.
        """
        return self.count == len(self.items)


# Your MyCircularDeque object will be instantiated and called as such:
# obj = MyCircularDeque(k)
# param_1 = obj.insertFront(value)
# param_2 = obj.insertLast(value)
# param_3 = obj.deleteFront()
# param_4 = obj.deleteLast()
# param_5 = obj.getFront()
# param_6 = obj.getRear()
# param_7 = obj.isEmpty()
# param_8 = obj.isFull()
  • python3 简化,用到python的一些函数,简化代码。
  • 插入前端我们用insert函数,插入后端我们用append。删除我们直接pop()就可以了,当然也可以用del,这里就没有展示了。
class MyCircularDeque:

    def __init__(self, k: int):
        """
        Initialize your data structure here. Set the size of the deque to be k.
        """
        self.items = []
        self.size = k

    def insertFront(self, value: int) -> bool:
        """
        Adds an item at the front of Deque. Return true if the operation is successful.
        """
        if len(self.items) == self.size:
            return False
        self.items.insert(0, value)
        return True

    def insertLast(self, value: int) -> bool:
        """
        Adds an item at the rear of Deque. Return true if the operation is successful.
        """
        if len(self.items) == self.size:
            return False
        self.items.append(value)
        return True

    def deleteFront(self) -> bool:
        """
        Deletes an item from the front of Deque. Return true if the operation is successful.
        """
        if len(self.items) == 0:
            return False
        self.items.pop(0)
        return True

    def deleteLast(self) -> bool:
        """
        Deletes an item from the rear of Deque. Return true if the operation is successful.
        """
        if len(self.items) == 0:
            return False
        self.items.pop()
        return True

    def getFront(self) -> int:
        """
        Get the front item from the deque.
        """
        if len(self.items) == 0:
            return -1
        return self.items[0]

    def getRear(self) -> int:
        """
        Get the last item from the deque.
        """
        if len(self.items) == 0:
            return -1
        return self.items[-1]

    def isEmpty(self) -> bool:
        """
        Checks whether the circular deque is empty or not.
        """
        return len(self.items) == 0

    def isFull(self) -> bool:
        """
        Checks whether the circular deque is full or not.
        """
        return len(self.items) == self.size


# Your MyCircularDeque object will be instantiated and called as such:
# obj = MyCircularDeque(k)
# param_1 = obj.insertFront(value)
# param_2 = obj.insertLast(value)
# param_3 = obj.deleteFront()
# param_4 = obj.deleteLast()
# param_5 = obj.getFront()
# param_6 = obj.getRear()
# param_7 = obj.isEmpty()
# param_8 = obj.isFull()
# leetcode submit region end(Prohibit modification and deletion)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值