您当前的位置: 首页 > 

宝哥大数据

暂无认证

  • 1浏览

    0关注

    1029博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

设计循环双端队列

宝哥大数据 发布时间:2019-10-15 17:05:49 ,浏览量:1

1.1、使用数据,模拟队列,通过已存入的元素个数,控制数据移动的范围

insertFront: 将0~size-1位的元素向后移动,新数据插入0 deleteFront: 将1~size-1位的元素向前移动,然后将第size-1位元素清空。

缺点: 需要大量的移动数据。
class MyCircularDeque:

    def __init__(self, k: int):
        """
        Initialize your data structure here. Set the size of the deque to be k.
        """
        self.dequeue = [0] * k
        self.size = 0
        self.c = 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.isEmpty():
            self.dequeue[0] = value
            self.size += 1
            return True
        
        #移位
        for i in range(self.size):
            self.dequeue[self.size-i] = self.dequeue[self.size-i-1]
        self.dequeue[0] = value
        self.size += 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.dequeue[self.size] = value
        self.size += 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
        
        for i in range(1, self.size):
            self.dequeue[i-1] = self.dequeue[i]
        self.dequeue[self.size-1] = 0
        self.size -= 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
        
        self.dequeue[self.size-1] = 0
        self.size -= 1
        return True
        

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

    def getRear(self) -> int:
        """
        Get the last item from the deque.
        """
        if self.isEmpty():
            return -1
        else:
            return self.dequeue[self.size - 1]
        

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

    def isFull(self) -> bool:
        """
        Checks whether the circular deque is full or not.
        """
        return self.size == self.c
关注
打赏
1587549273
查看更多评论
立即登录/注册

微信扫码登录

0.0451s