0210leetcode brushes 5 python questions

88

Description of the title;
given you two ordered integer arrays nums1 and nums2, please merge nums2 into nums1 to make nums1 an ordered array.
Initialize the number of elements of nums1 and nums2 to m and n respectively. You can assume that the space size of nums1 is equal to m + n, so that it has enough space to store the elements from nums2.

Example:
Insert picture description here
Answer:

class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """

        '''
        nums1[m:]=nums2[:]
        nums1.sort()
        '''
        i,j,k=m-1,n-1,m+n-1
        while i>=0 and j>=0:
            if nums1[i]<nums2[j]:
                nums1[k]=nums2[j]
                k-=1
                j-=1
            else:
                nums1[k]=nums1[i]
                k-=1
                i-=1
        if j>=0:
            while j>=0:
                nums1[k]=nums2[j]
                k-=1
                j-=1

1423

Title description:
Several cards are arranged in a row, and each card has a corresponding point. The number of points is given by the integer array cardPoints.
For each action, you can take a card from the beginning or the end of the line, and in the end you must take exactly k cards.
Your points are the sum of the points of all the cards in your hand.
Give you an integer array cardPoints and an integer k, please return the maximum number of points you can get.

Example:
Insert picture description here
Answer:

class Solution:
    def maxScore(self, cardPoints: List[int], k: int) -> int:
        #既然左右两边都可以取,那就直接看左边取n个,右边取k-n个
        res = 0
        total = [0]
        flag = 0
        for i in cardPoints: # 先记录累加和
            flag += i
            total.append(flag)
        for i in range(0,k+1): # i是左边分配的位置
            flag = total[i]+total[-1]-total[-1-k+i]
            res = max(flag,res)
        return res

Sword refers to offer34

Title description:
Input a binary tree and an integer, and print out all paths where the sum of node values ​​in the binary tree is the input integer. Starting from the root node of the tree and going down to the nodes passed by the leaf nodes form a path.

Example:
Insert picture description here
Answer:

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

class Solution:
    def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
        res, path = [], []
        def recur(root, tar):
            if not root: return
            path.append(root.val)
            tar -= root.val
            if tar == 0 and not root.left and not root.right:
                res.append(list(path))
            recur(root.left, tar)
            recur(root.right, tar)
            path.pop()

        recur(root, sum)
        return res

Sword refers to offer56-I

Title description:
Except for two numbers in an integer array, the other numbers appear twice. Please write a program to find these two numbers that only appear once. The required time complexity is O(n), and the space complexity is O(1).

Example:
Insert picture description here
Answer:

class Solution:
    def singleNumbers(self, nums: List[int]) -> List[int]:
        ret, index = 0, 0
        for n in nums:
            ret ^= n
        # 找从右向左数第几位不同,也就是第index位
        while ret & 1 == 0:
            index += 1
            ret >>= 1
        r1, r2 = 0, 0
        for n in nums:
            if (n >> index) & 1 == 0:
                r1 ^= n
            else:
                r2 ^= n
        return [r1, r2]

Sword refers to offer68-II

Title description:
Given a binary tree, find the nearest common ancestor of two specified nodes in the tree.
The definition of the nearest common ancestor in Baidu Encyclopedia is: "For the two nodes p and q of the rooted tree T, the nearest common ancestor is expressed as a node x, satisfying that x is the ancestor of p and q and the depth of x is as large as possible (A node can also be its own ancestor)."
For example, given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]
Insert picture description here
Example:
Insert picture description here
Solution:

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

class Solution:
    def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
        # 求出到两个节点的路径,然后遍历数组,不相等的前一个为解
        if root == None:
            return None
        if root==p or root == q:
            return root
        left = self.lowestCommonAncestor(root.left,p,q)  # 左右子树寻找p,q
        right = self.lowestCommonAncestor(root.right,p,q)

        if left and right:        # 都找到了,一边一个
            return root
        if not left:              # 左子树没有,即都在右子树   
            return right
        if not right:
            return left

Guess you like

Origin blog.csdn.net/yeqing1997/article/details/113685183