leetcode每日一练

DATAwhale编程第六期任务一

一、任务说明:
1、栈
用数组实现一个顺序栈
用链表实现一个链式栈
编程模拟实现一个浏览器的前进、后退功能

2、队列
用数组实现一个顺序队列
用链表实现一个链式队列
实现一个循环队列

3、链表
实现单链表、循环链表、双向链表,支持增删操作
实现单链表反转
实现两个有序的链表合并为一个有序链表
实现求链表的中间结点

二、对应的 LeetCode 练习题

一、栈

1、Valid Parentheses(有效的括号)
https://leetcode.com/problems/valid-parentheses/

    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack=[]
        length=len(s)
        if (length%2):
            return False
            
   
      for i in s:
            if not stack:
                stack.append(i)
                continue
            top=stack[-1]
            if top=='(':
                if i==')':
                    stack.pop()
                else:
                    stack.append(i)
            elif top=='{':
                if i=='}':
                    stack.pop()
                else:
                    stack.append(i)
            elif top=='[':
                if i==']':
                    stack.pop()
                else:
                    stack.append(i)
            else:
                     return False
        if not stack:
                return True
        else:
                return False
           

2、Longest Valid Parentheses(最长有效的括号)
https://leetcode.com/problems/longest-valid-parentheses/

    def longestValidParentheses(self, s):
        """
        :type s: str
        :rtype: int
        """
        n=len(s)
        stack,index_stack=[],[-1]
        max_len=0
        for i in range(n):
            if s[i]=='(':
                stack.append(s[i])
                index_stack.append(i)
            else:
                if stack!=[]:
                    stack.pop()
                    index_stack.pop()
                else:
                    index_stack.append(i)
        if len(index_stack)==1:
            max_len=len(s)
        else:
            index_stack.append(len(s))
        for i in range(len(index_stack)-1):
            if index_stack[i+1]-index_stack[i]!=1:
                if max_len<index_stack[i+1]-index_stack[i]-1:
                    max_len=index_stack[i+1]-index_stack[i]-1
        return max_len

3、Evaluate Reverse Polish Notatio(逆波兰表达式求值)
https://leetcode.com/problems/evaluate-reverse-polish-notation/

    def evalRPN(self, tokens):
        """
        :type tokens: List[str]
        :rtype: int
        """
        stack=[]
        for t in tokens:
            if t not in['+','-','*','/']:
                stack.append(int(t))
            else:
                r,l=stack.pop(),stack.pop()
                if t=="+":
                     stack.append(l+r)
                elif t=="-":
                    stack.append(l-r)
                elif t=="*":
                    stack.append(l*r)
                elif t=="/":
                     stack.append(l/r)
                else:
                    if l*r<0 and l%r!=0:
                         stack.append(l/r+1)
                    else:
                         stack.append(l/r)
        return stack.pop()


二、队列
1、Design Circular Deque(设计一个双端队列)
https://leetcode.com/problems/design-circular-deque/


    def __init__(self, k):
        """
        Initialize your data structure here. Set the size of the deque to be k.
        :type k: int
        """
        self.a=[None]*k
        self.k=k
        self.sz=0
        self.b=k-1
        self.f=0
        
    def prev_idx(self,i):
        if i==0:
            return self.k-1
        else:
            return i-1
        
        
    def next_idx(self,i):
        return (i+1)%self.k

    
    def insertFront(self, value):
        """
        Adds an item at the front of Deque. Return true if the operation is successful.
        :type value: int
        :rtype: bool
        """
        if self.sz== self.k:
            return False
        self.f=self.prev_idx(self.f)
        self.a[self.f]=value
        self.sz+=1
        return True

    def insertLast(self, value):
        """
        Adds an item at the rear of Deque. Return true if the operation is successful.
        :type value: int
        :rtype: bool
        """
        if self.sz==self.k:
            return False
        self.b=self.next_idx(self.b)
        self.a[self.b]=value
        self.sz +=1
        return True
        

    def deleteFront(self):
        """
        Deletes an item from the front of Deque. Return true if the operation is successful.
        :rtype: bool
        """
        if self.sz==0:
            return False
        self.f=self.next_idx(self.f)
        self.sz-=1
        
        return True

    def deleteLast(self):
        """
        Deletes an item from the rear of Deque. Return true if the operation is successful.
        :rtype: bool
        """
        if self.sz==0:
            return False
        self.b=self.prev_idx(self.b)
        self.sz-=1
        
        return True
        

    def getFront(self):
        """
        Get the front item from the deque.
        :rtype: int
        """
        if self.sz==0:
            return -1
        return self.a[self.f]
        

    def getRear(self):
        """
        Get the last item from the deque.
        :rtype: int
        """
        if self.sz==0:
            return -1
        return self.a[self.b]

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

    def isFull(self):
        """
        Checks whether the circular deque is full or not.
        :rtype: bool
        """
        
        return self.sz==self.k

# 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()


2、Sliding Window Maximum(滑动窗口最大值)
https://leetcode.com/problems/sliding-window-maximum/

    def maxSlidingWindow(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        if not nums:
            return []
        res=[]
        for i in range (len(nums)-k +1):
            temp=max(nums[i:i+k])
            res.append(temp)
        return res


三、链表
1、Linked List Cycle I(环形链表)
https://leetcode.com/problems/linked-list-cycle/

# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        try:
            slow=head
            fast=head.next

            while slow is not fast:

                slow=slow.next
                fast=fast.next.next
            return True
        except:
            return False


2、Merge k Sorted Lists(合并 k 个排序链表)
https://leetcode.com/problems/merge-k-sorted-lists/

# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        from heapq import heappush,heappop,heapreplace,heapify
        dummy=node=ListNode(0)
        h=[(li.val,li) for li in lists if li]
        heapify(h)
        while h:
            v,li=h[0]
            if li.next is None:
                heappop(h)
            else:
                heapreplace(h,(li.next.val,li.next))
            node.next=li
            node=node.next
        return dummy.next


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值