算法与数据结构 / 44

算法练习:最近点与BST第二大值

数据结构、边界条件与实现过程。 算法练习:最近点与BST第二大值。

阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。

2. K Closest Points to Origin

Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0). The distance between two points on the X-Y plane is the Euclidean distance (i.e., √((x1 - x2)^2 + (y1 - y2)^2). You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).

  • Example 1:
    Input: points = [[1,3],[-2,2]], k = 1
    Output: [[-2,2]]

  • Example 2:
    Input: points = [[3,3],[5,-1],[-2,4]], k = 2
    Output: [[3,3],[-2,4]] or [[-2,4],[3,3]]

TC=O(Nlog⁡K)TC=O(N\log{K})
SC=O(K)SC=O(K)

PYTHON · 仅供阅读
import heapq

# 逻辑上的max heap
class Solution:
    def kCloset(self, points, k):
        if len(points) <= k:
            return points

        h = []
        for i in range(len(points)):
            dist = -points[i][0] ** 2 - points[i][1] ** 2
            heapq.heappush(h, (dist, i))
            if len(h) > k:
                heapq.heappop(h)
                
        ret = []
        for item in h:
            ret.append(points[item[1]])
        return ret

3. Find the second largest value inside a binary search tree. You can assume that a node inside this tree only contains a single value.

For this problem, the requirement is to solve this with recursion. If there is any subroutine you need, it also need to be written with recursion.

  • Example 1:
    Input:
PLAINTEXT · 仅供阅读
               2
             /   \
            1     3

Output:2

  • Example 2:
    Input:
PLAINTEXT · 仅供阅读
               8
             /   \
            3    10 
          /  \     \
         1    6    14
             / \   /
            4  7  13

Output:13

Solution 1: inorder traversal
T:O(N)T:O(N)
S:O(N)S:O(N)

Solution 2:
T:O(h)T:O(h)
S:O(h)S:O(h)

PYTHON · 仅供阅读
class Solution:
    def secondLargest(self, root):
        self.cnt = 0
        self.result = None
        self.traverse(root)
        return self.result if self.result != None else -2147283648
    
    def traverse(self, root):
        if not root:
            return
        self.traverse(root.right)
        self.cnt += 1
        if self.cnt == 2:
            self.result = root.val
            return
        if self.cnt > 2:
            return
        self.traverse(root.left)

Solution 3:
T:O(h)T:O(h)
S:O(h)S:O(h)

PYTHON · 仅供阅读
def find_largest(root):
    if not root:
        return

    # 右子树不存在,左子树比根一定小,跟是最大的,返回根节点
    if not root.right:
        return root
    
    # 右子树存在,根一定比右子树小,根一定不是最大的,在右子树里继续搜索最大的
    return find_largest(root.right)

def find_2nd_largest(root):
    if not root:
        return
    
    # Case 1 右子树不存在,root最大的。左子树中最大的就是第二大
    if not root.right:
        return find_largest(root.left)
    
    # Case 2 右子树没有子树,根的右节点是最大的
    # 左子树 < 根 < 根的右节点,根是第二大
    right = root.right
    if not right.left and not right.right:
        return root
    
    # Case 3 结果在右子树中,递归调用
    return find_2nd_largest(root.right)

整理参考资料