Leetcode习题螺旋矩阵,旋转链表

螺旋矩阵

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix: return []
        m=len(matrix) #行
        n=len(matrix[0]) #列

        layer_num=(min(m,n)+1)//2 #有多少层
        res_list=[] #保持结果

        for lr in range(layer_num):
            start=lr #左上角
            last_col=n-lr-1 #该层最后一列索引
            last_row=m-lr-1

            for i in range(start, last_col+1): #遍历左右
                res_list.append(matrix[start][i]) #加入此行?
            for j in range(start+1,last_row+1): #遍历上下,+1去重
                res_list.append(matrix[j][last_col]) #加入此列

            if last_col!=start and last_row!=start:
                for ii in range(last_col-1,start-1,-1): # 右→左
                    res_list.append(matrix[last_row][ii]) #右到左的顺序放入
                for ij in range(last_row-1,start,-1): #下→上
                    res_list.append(matrix[ij][start]) #下到上的顺序放入

        return res_list

螺旋矩阵

class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        x=1
        y=1
        direct=[(0,1),(1,0),(0,-1),(-1,0)] #变化量
        turn=0
        ans=[]
        ans.append([-1]*(n+2)) 
        for i in range(0,n):
                ans.append([-1]+[0]*n+[-1]) #-1为边界,遇到边界就转向
            ans.append([-1]*(n+2))

            for i in range(1,n*n+1):
                if ans[x][y]==0:
                    ans[x][y]=i
                if ans[x+direct[turn][0]][y+direct[turn][1]]!=0:
                    turn=(turn+1)%4
                x+=direct[turn][0]
                y+=direct[turn][1]
                
        re_ans=[a[1:n+1] for a in ans[1:n+1]]
        return re_ans

旋转链表

class Solution:
    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        if not head or not head.next or not k: return head
        tail, count= head, 1 #头尾,链表长度
        
        while tail.next: 
            tail = tail.next #找到旧链表尾部
            count += 1 
        k = k % count #旋转多少次
        if k == 0:
            return head
        newTail = newHead = head
        for i in range(count - k): #目前的头部
            newHead = newHead.next
        for j in range(count - k - 1): 
            newTail = newTail.next
        newTail.next = None #打破闭环
        tail.next = head
        return newHead
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值