LeetCode算法题python解法:25. Reverse Nodes in k-Group
Posted slarker
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode算法题python解法:25. Reverse Nodes in k-Group相关的知识,希望对你有一定的参考价值。
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
Example:
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
Note:
- Only constant extra memory is allowed.
- You may not alter the values in the list‘s nodes, only nodes itself may be changed.
题意大概是给定链表和一个参数K,每K个节点反转一次,剩下的节点不够K个则不反转。
这个题目对时间复杂度要求比较高,遍历到列表中通过reverse反转肯定是超时的,只能在链表上直接操作反转。
代码如下:
class Solution: def reverseKGroup(self, head, k): if head==None: return head out=[] while True: #遍历链表,将链表放到一个list中,方便后续反转指向的操作 out.append(head) if head.next==None: break head=head.next if k>len(out): return out[0] st=0 end=k while True: for i in range(st+1,end): #将每K个范围内的节点指向反转 out[i].next=out[i-1] if end+k<=len(out): #判断K范围内最后一节点的指向,如果还存在下一个K则指向下个K的最后一个值 out[st].next=out[end+k-1] elif st+k>=len(out): #如果没有下个K则指向None out[st].next=None elif st+k<len(out)<end+k: #如果剩下的数不够凑齐一个K,则指向剩下列表的第一个数 out[st].next=out[end] st+=k end+=k if len(out) < end: break if len(out)<2: return out[0] return out[k-1]
以上是关于LeetCode算法题python解法:25. Reverse Nodes in k-Group的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode算法题python解法:23. Merge k Sorted Lists
LeetCode算法题python解法:17. Letter Combinations of a Phone Number
LeetCode算法题-Move Zeroes(Java实现-三种解法)
LeetCode算法题-Valid Perfect Square(Java实现-四种解法)