mengyushi / LeetCode

4 stars 0 forks source link

swap node & matrix sum #239

Open mengyushi opened 4 years ago

mengyushi commented 4 years ago

https://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=488521&highlight=Uber%2BATG 一道利口斯尔,一道利口散灵思

mengyushi commented 4 years ago
  1. Swap Nodes in Pairs
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        '''
        dummy->1->2->3->4->None
               [  ]  [  ]
        pre    p nxt next_p
                       pre  p
        '''

        dummy = ListNode(None)
        pre = dummy
        p = head

        while p and p.next:
            next_p = p.next.next
            nxt = p.next
            pre.next = nxt
            nxt.next = p
            pre = p
            p = next_p

        pre.next = p
        return dummy.next
mengyushi commented 4 years ago

class NumMatrix:
    '''
    DP

    '''
    def __init__(self, matrix: List[List[int]]):
        M, N = len(matrix), len(matrix) and len(matrix[0])
        self.AGG = [[0] * (N+1) for _ in range(M+1)]
        for i in range(M):
            for j in range(N):
                self.AGG[i+1][j+1] = matrix[i][j] + self.AGG[i][j+1] + self.AGG[i+1][j] - self.AGG[i][j]

    def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
        return self.AGG[row2+1][col2+1] + self.AGG[row1][col1] - self.AGG[row1][col2+1] - self.AGG[row2+1][col1]

# Your NumMatrix object will be instantiated and called as such:
# obj = NumMatrix(matrix)
# param_1 = obj.sumRegion(row1,col1,row2,col2)