4.4leetcode日记

977. 有序数组的平方(E)

这道题看起来很简单,但是却复习了几个知识点及细节。
首先我用的map函数
map(lambda x:x*x,LIST)
然后其实map return回来的格式是迭代器并不是LIST
所以要手动转化成list(map())的形式
然后return list.sort()
There is another error.
list.sort can only change in the previous list,not return a new List.
So I have to use : list.sort() return list
or return sorted(list)
map()

Point:filter reduce and map

将序列中的元素通过处理函数处理后返回一个新的列表
filter()

将序列中的元素通过函数过滤后返回一个新的列表
reduce()

将序列中的元素通过一个二元函数处理返回一个结果
将上面三个函数和lambda结合使用

li = [1, 2, 3, 4, 5]
# 序列中的每个元素加1
map(lambda x: x+1, li) # [2,3,4,5,6]
 
# 返回序列中的偶数
filter(lambda x: x % 2 == 0, li) # [2, 4]
 
# 返回所有元素相乘的结果
reduce(lambda x, y: x * y, li) # 1*2*3*4*5 = 120

230. Kth Smallest Element in a BST(M)

这道题其实蛮简单的,但是让我想起了二叉树的前后中序遍历,运用之前带标签元祖的方法解决了这个问题。也算是复习了一遍二叉树的遍历,这个还是要多写写,要不然就忘了。

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

class Solution:
    def kthSmallest(self, root: TreeNode, k: int) -> int:
        if not root:
            return None
        return self.LDR([(0,root)],k)
    def LDR(self,temp,k):
        res=[]
        while len(res)<k:
            n,m=temp.pop()
            if n==1:
                res.append(m.val)
            else:
                if m.right:
                    temp.append((0,m.right))
                temp.append((1,m))
                if m.left:
                    temp.append((0,m.left))
        return res[-1]

猜你喜欢

转载自blog.csdn.net/qq_43100883/article/details/89020089
4.4