Study Plan For Algorithms - Part43

1. 最大矩形
给定一个仅包含 0 和 1 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。

class Solution:
    def maximalRectangle(self, matrix: List[List[str]]) -> int:
        if not matrix:
            return 0
        rows, cols = len(matrix), len(matrix[0])
        heights = [0] * cols
        max_area = 0
        for i in range(rows):
            for j in range(cols):
                if matrix[i][j] == '1':
                    heights[j] += 1
                else:
                    heights[j] = 0
            stack = []
            for j in range(cols + 1):
                while stack and (j == cols or heights[stack[-1]] > heights[j]):
                    height = heights[stack.pop()]
                    width = j - (stack[-1] if stack else -1) - 1
                    max_area = max(max_area, height * width)
                stack.append(j)
        return max_area

2. 分隔链表
给定一个链表的头节点 head 和一个特定值 x ,请对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。保留 两个分区中每个节点的初始相对位置。

class Solution:
    def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
        less_head = ListNode()
        greater_head = ListNode()
        less_ptr = less_head
        greater_ptr = greater_head

        curr = head
        while curr:
            if curr.val < x:
                less_ptr.next = curr
                less_ptr = less_ptr.next
            else:
                greater_ptr.next = curr
                greater_ptr = greater_ptr.next
            curr = curr.next

        greater_ptr.next = None
        less_ptr.next = greater_head.next
        return less_head.next
posted @ 2024-09-26 00:43  WindMay  阅读(8)  评论(0编辑  收藏  举报