Uriel's Corner

Research Associate @ Harvard University / Research Interests: Computer Vision, Biomedical Image Analysis, Machine Learning
posts - 0, comments - 50, trackbacks - 0, articles - 594
交换单链表位置k和n-k的两个元素,链表元素个数事先未知(只交换两个元素的值即可,不用调整链表指针)


 1 #1721
 2 #Runtime: 1265 ms (Beats 56.45%)
 3 #Memory: 91.1 MB (Beats 69.35%)
 4 
 5 class Solution(object):
 6     def swapNodes(self, head, k):
 7         """
 8         :type head: ListNode
 9         :type k: int
10         :rtype: ListNode
11         """
12         t = 1
13         head2, head3 = head, head
14         while t < k:
15             head2 = head2.next
16             head3 = head3.next
17             t += 1
18         n = t
19         while head3:
20             head3 = head3.next
21             n += 1
22         t = 0
23         head3 = head
24         while t < n - k - 1:
25             head3 = head3.next
26             t += 1
27         head2.val, head3.val = head3.val, head2.val
28         return head

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理