python算法第二阶段

前序+后序->层次遍历

import json
from typing import List
"""
前序:[1,2,4,5,3,6,7]
后序:[4,5,2,6,7,3,1]
[1, 2, 3, 4, 5, 6, 7, null, null, null, null, null, null, null, null]
关键点:
左分支有 LL 个节点。我们知道左分支的头节点为 pre[1],但它也出现在左分支的后序表示的最后。
所以 pre[1] = post[L-1](因为结点的值具有唯一性),因此 L = post.indexOf(pre[1]) + 1
"""
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> TreeNode:
        if not preorder:
            return None
        root=TreeNode(preorder[0]) #根结点,注意TreeNode类没有单独设置根赋值,所以不能写成TreeNode(0)
        if len(preorder)==1:
            return root

        L=postorder.index(preorder[1])+1
        root.left=self.constructFromPrePost(preorder[1:L+1],postorder[:L]) #前序跳过第一位(根结点),后序不需要跳过
        root.right=self.constructFromPrePost(preorder[L+1:],postorder[L:-2]) #这里postorder[L:-1]到-2或-1或-3似乎对结果都没有影响
        return root
def stringToIntegerList(input):
    return json.loads(input)
def treeNodeToString(root):
    if not root:
        return "[]"
    output = ""
    queue = [root] #关键点:初始化一个list表示队列,并且内部是按TreeNode结果存储的
    current = 0
    while current != len(queue):
        node = queue[current]
        current = current + 1

        if not node:
            output += "null, "
            continue

        output += str(node.val) + ", " #注意看输入有没有空格
        queue.append(node.left)
        queue.append(node.right)
    return "[" + output[:-2] + "]"

def main():
    import sys
    import io
    def readlines():
        for line in io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8'):
            yield line.strip('\n')

    lines = readlines()
    while True:
        try:
            line = next(lines)
            preorder = stringToIntegerList(line);
            line = next(lines)
            postorder = stringToIntegerList(line);
            ret = Solution().constructFromPrePost(preorder, postorder)
            out = treeNodeToString(ret);
            print(out)
        except StopIteration:
            break

if __name__ == '__main__':
    main()

绝对差不超过限制的最长连续数组长度

需参考python封装好的sortedcontainers

mac M1操作系统,采样python3 setup.py install 安装,下载tar.gz

import json
from typing import List
from sortedcontainers import SortedList

class Solution:
    def longestSubarray(self, nums: List[int], limit: int) -> int:
        s = SortedList() #初始化为空 有序list
        n = len(nums)
        left = right = ret = 0

        while right < n:
            s.add(nums[right])
            print("s[-1]=",s[-1],"s[0]=",s[0])
            while s[-1] - s[0] > limit: #s[-1]对于每一轮是新加入的元素
                s.remove(nums[left]) #从左到右移除那些不满足limit条件的元素,以保证s[0]总是满足要求的第一个元素
                left += 1
            ret = max(ret, right - left + 1) #长度比较,因为left和right都是从0开始的,所有还得加1
            right += 1

        return ret

def stringToIntegerList(input):
    return json.loads(input)

def main():
    import sys
    import io
    def readlines():
        for line in io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8'):
            yield line.strip('\n')

    lines = readlines()
    while True:
        try:
            line = next(lines)
            nums = stringToIntegerList(line)
            line = next(lines)
            limit = int(line);

            ret = Solution().longestSubarray(nums, limit)

            out = str(ret);
            print(out)
        except StopIteration:
            break

if __name__ == '__main__':
    main()

150. 逆波兰表达式求值

import json
from typing import List

def stringToStrList(input): #输入进来的input虽然有[]但不是list所以处理取值之后inputValues需加上[]
    input=input.strip()

    input=input[1:-1] #去掉首位中括号
    print(input)
    if not input:
        return None
    inputValues=[s.strip() for s in input.split(',')] #去除逗号,但有加入到[]会自动生成新的逗号,逗号后多一个空格,每一个元素会带上单引号
    return inputValues

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        f1 = lambda a, b: a + b #相当于一个匿名函数get(a,b): return a + b
        f2 = lambda a, b: a - b
        f3 = lambda a, b: a * b
        f4 = lambda a, b: int(a / b)
        maps = {'+': f1, '-': f2, '*': f3, '/': f4}
        stack = [] #或定义成list()
        for i in tokens:
            if i in maps: #当遇到符号时
                a = stack.pop() #这个弹出的顺序不能弄错,a先弹出,在进行减法和除法时,应b-a或b-a
                b = stack.pop()
                stack.append(maps[i](b, a)) #maps[i](b, a) 就是b+a 或b-a 或 b*a 或 b-a 符号根据i选择
            else: #不是符号时,把数值给提取出来,这样stack里面就都是数值
                i = int(i)
                stack.append(i)
        return stack[-1] #弹出计算好的元素刚好是栈顶元素

def main():
    import sys
    import io
    def readlines():
        for line in io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8'):
            yield line.strip('\n')

    lines = readlines()
    while True:
        try:
            line = next(lines)
            hours = stringToStrList(line)
            print(hours)
            ret = Solution().evalRPN(hours)
            out = str(ret);
            print(out)
        except StopIteration:
            break

if __name__ == '__main__':
    main()

运行效果

[2,1,+,3,*]
2,1,+,3,*
['2', '1', '+', '3', '*']
9

N 皇后-回溯

class Solution:
    def __init__(self): #注意别写错四个下划线
        self.res=[]
    def isCheck(self,trace,row,column):
        nLen=len(trace)
        #column
        for item in trace:
            if item[column]=='Q':
                return False
        #上右
        for i,j in zip(range(row-1,-1,-1),range(column+1,nLen)):
            if trace[i][j]=='Q':
                return False

        #上左
        for i,j in zip(range(row-1,-1,-1),range(column-1,-1,-1)): #注意行列都要倒序
            if trace[i][j]=='Q':
                return False
        return True
    def replaceChar(self,trace,idx,char):
        strList=list(trace)
        strList[idx]=char
        s=''.join(strList)
        return s
    def backtrace(self,trace,row):
        if(len(trace)==row):
            ret=list(trace)
            self.res.append(ret)
            return 

        for column in range(len(trace)): #注意不要写成trace[row]
            if (not self.isCheck(trace,row,column)):
                continue
            #注意下面三行代码要放在for循环里面
            trace[row]=self.replaceChar(trace[row],column,'Q') #注意传入的是column
            self.backtrace(trace,row+1)
            trace[row]=self.replaceChar(trace[row],column,'.')

    def solveNQueens(self, n: int) -> List[List[str]]:
        s='.'*n
        trace = [s]*n
        self.backtrace(trace,0)
        return self.res #存入到了初始化数组res里面了,直接调用即可

决策单调性优化

两位有序list合并成一个list后求中位数

解法:第k小数,参考视频讲解1具体代码

tarjan算法

参考tarjan

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Alex-panda

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

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

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

打赏作者

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

抵扣说明:

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

余额充值