leetcode 54\59\61

54 螺旋矩阵

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        m = len(matrix)
        n = len(matrix[0])
        layer_num = (min(m,n) + 1)//2
        res = []
        for layer in range(layer_num):
            start = layer
            last_col = n-1-layer #最后一列的下标
            last_row = m-1-layer #最后一行的下标

            for j in range(start, last_col+1): #from left to right
                res.append(matrix[start][j])
            for j in range(start+1, last_row+1): #from top to bottom
                res.append(matrix[j][last_col])

            if start != last_row and start != last_col:
                for j in range(last_col-1,start-1,-1): #from right to left
                    res.append(matrix[last_row][j])
                for j in range(last_row-1, start, -1): # from bottom to top
                    res.append(matrix[j][start])
        return res

59 螺旋矩阵Ⅱ

class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        matrix = [[0]*n for _ in range(n)]
        # print(matrix)
        layer_num = (n+1)//2
        count = 0
        for layer in range(layer_num):
            start = layer
            last_idx = n-1-layer
            # last_row = n-1-layer
            for i in range(start,last_idx+1):
                count += 1
                matrix[start][i] = count
            for i in range(start+1, last_idx+1):
                count += 1
                matrix[i][last_idx] = count
            
            if start != last_idx:
                for i in range(last_idx-1, start-1,-1):
                    count += 1
                    matrix[last_idx][i] = count
                for i in range(last_idx-1, start, -1):
                    count += 1
                    matrix[i][start] = count
        return matrix

61 旋转链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        if not head: return head
        p = head
        n = 1
        while p.next:
            n += 1
            p = p.next
        k = k%n  # 防止循环太多无用次数
        
        for i in range(k):
            pre = None
            cur = head
            while cur.next:
                pre = cur
                cur=cur.next

            if not pre:
                return head

            cur.next = head
            pre.next = None
            head = cur
        return head
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值