Python习题集(2)

Q11 递归--爬楼问题

You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

思路:斐波那契数列,爬楼问题,转化成构建斐波那契数列。

class Solution:
    def climbStairs(self, n: int) -> int:
        a,b=0,1
        for i in range(n+1):
            a,b = b, a+b
        return a

Q12 递归--斐波那契数

The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.

Given n, calculate F(n)

思路:依然是基本构建累加的思路

class Solution:
    def fib(self, n: int) -> int:
        a,b=0,1
        for i in range(n):
            a,b=b,a+b
        return a

Q13 递归--二叉树求和

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

leaf is a node with no children.

Eg:

Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: The root-to-leaf path with the target sum is shown

思路:二叉树遍历。

链接:python算法学习——二叉树_零度不知寒的博客-CSDN博客_二叉树python算法​​​​​​

           二叉树(python实现)_不吃鱼的猫748的博客-CSDN博客_二叉树python

# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def hasPathSum(self, root, sum):
        if not root:
            return False

        if not root.left and not root.right and root.val == sum:
            return True
        
        sum -= root.val

        return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum)

Q14--分治

You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.

Merge all the linked-lists into one sorted linked-list and return it.、

思路:

from operator import attrgetter

class Solution:
    # @param a list of ListNode
    # @return a ListNode
    def mergeKLists(self, lists):
        sorted_list = []
        for head in lists:
            curr = head
            while curr is not None:
                sorted_list.append(curr)
                curr = curr.next

        sorted_list = sorted(sorted_list, key=attrgetter('val'))
        for i, node in enumerate(sorted_list):
            try:
                node.next = sorted_list[i + 1]
            except:
                node.next = None

        if sorted_list:
            return sorted_list[0]
        else:
            return None

Q15--分治,求数量最多元素

Given an array nums of size n, return the majority element.

The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.

import collections

def majorityElement(self, nums: List[int]) -> int:
        count_dict = collections.Counter(nums)
        majority_count = len(nums)/2
        for key, value in count_dict.items():
            if value > majority_count:
                return key

Q16--分治 矩阵

Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:

  • Integers in each row are sorted in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom

class Solution:
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if len(matrix) == 0: return False
        # we initialize the pointer at the bottom-left of the matrix
        r,c = len(matrix)-1,0
        while r >=0 and c <len(matrix[0]):
            if matrix[r][c] == target:
                return True
            else:
                if matrix[r][c] < target:
                    c += 1
                else:
                    r -= 1
        return False

Q17--单调栈 (数据结构),最大矩形面积

Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.

class Solution:
    def largestRectangleArea(self, heights: List[int]) -> int:
        if not heights:
            return 0
        stack=[0]
        maxarea=0
        for index in range(1,heights.__len__()):
            if(heights[index]>heights[stack[-1]]):
                stack.append(index)
            elif(heights[index]==heights[stack[-1]]):
                continue
            else:
                while stack and heights[index]<heights[stack[-1]]:
                    top=stack.pop()
                    distance=index-top
                    maxarea=max(maxarea,distance*heights[top])
                heights[top]=heights[index]
                stack.append(top)
                stack.append(index)
        for x in range(stack.__len__()):
            maxarea=max(maxarea,heights[stack[x]]*(heights.__len__()-stack[x]))
        return maxarea

Q18--单调栈

Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.

    # O(n)
    def largestRectangleArea(self, heights: List[int]) -> int:
        stack = [0]
        heights.append(0)
        
        res = 0
        for right in range(1,len(heights)):
            while stack and heights[stack[-1]] > heights[right]:
                h = heights[stack.pop()]
                left = -1 if not stack else stack[-1] # because pop operation, left = stack.pop() is not the left boundary
                w = right - left -1
                res = max(res,h*w)
            stack.append(right)
        return res
    
    # O(n2)
    def maximalRectangle(self, matrix: List[List[str]]) -> int:
        if not matrix:
            return 0
        heights = [0]*len(matrix[0])
        res = 0
        for row in matrix:
            for i in range(len(row)):
                heights[i] = heights[i] + int(row[i]) if int(row[i]) else 0
            res = max(res,self.largestRectangleArea(heights))
        return res

Q19--单调栈(日常气温)

Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.

class Solution:
	def dailyTemperatures(self, T: List[int]) -> List[int]:        
		stack=[]
		res=[0]*len(T)
		tem=list(enumerate(T))        
		for i,j in tem:
			while stack and j>T[stack[-1]]:
				res[stack[-1]]=i-stack[-1]
				stack.pop()            
			stack.append(i)
		return res

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

[Karel]

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

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

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

打赏作者

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

抵扣说明:

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

余额充值