leetcode 每日一题 61. 旋转链表

先闭环后开环

思路:

先找到链表最后一个非空节点tail,通过tail.next=head使链表形成闭环。接着从头开始找到第n-k%n 个节点当作new_tail,new_tail.next为new_head,接着再令new_tail.next为null进行开环,返回new_head即可。

代码:

class Solution:
    def getPermutation(self, n: int, k: int) -> str:
        factorials, nums = [1], ['1']
        for i in range(1, n):
            factorials.append(factorials[i - 1] * i)
            nums.append(str(i + 1))
        k -= 1
        output = []
        for i in range(n - 1, -1, -1):
            idx = k // factorials[i]
            k -= idx * factorials[i]
            output.append(nums[idx])
            del nums[idx]
        return ''.join(output)

 

posted @ 2020-06-06 13:24  nil_f  阅读(106)  评论(0)    收藏  举报