partition List Leetcode Python
来源:互联网 发布:四小票采集软件 编辑:程序博客网 时间:2024/06/05 02:19
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2
and x = 3,
return 1->2->2->4->3->5
.
算法复杂度O(n)
遍历一遍链表依次把小于X的值加到第一个链表后,大于等于X的加到第二个链表后。遍历完毕后再把第一个链表的尾巴指向第二链表的头。
返回第一个链表的头。
The time complexity is O(n), we need to go through the whole linklist and compare the tmp value with x. If the tmp value is smaller than X, we append it to the first linklist otherwise the second. Then append the head of the second linklist to the tail of the first linklist. Return the head of the first linklist.
I was also thing about just swap positions in the linklist but have no idea right now. If anyone have it please do not hesitate to leave me some message.
Below is the code:
# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = Noneclass Solution: # @param head, a ListNode # @param x, an integer # @return a ListNode def partition(self, head, x): dummy=ListNode(0) dummy.next=head dummy1=ListNode(0) dummy2=ListNode(0) head1=dummy1 head2=dummy2 tmp=head while tmp: if tmp.val<x: head1.next=tmp tmp=tmp.next head1=head1.next head1.next=None else: head2.next=tmp tmp=tmp.next head2=head2.next head2.next=None head1.next=dummy2.next head=dummy1.next return head
- partition List Leetcode Python
- [Leetcode][python]Partition List
- 【LeetCode with Python】 Partition List
- 【LEETCODE】86- Partition List [Python]
- LeetCode: Partition List
- LeetCode Partition List
- LeetCode: Partition List
- [Leetcode] Partition List **
- [Leetcode] Partition List
- [LeetCode] Partition List
- leetcode 81: Partition List
- [Leetcode] Partition List
- leetcode 118: Partition List
- [LeetCode]Partition List
- [leetcode]Partition List
- LeetCode-Partition List
- [leetcode] Partition List
- LeetCode - Partition List
- 创业公司 股权分配| 从西少爷股权纷争看初创公司找合伙人与股权分配
- #Factorial Trailing Zeros#
- HTTP协议基础和TOMCAT环境配置
- 初识CDN
- 一个使用servlet随机生成双色球的代码
- partition List Leetcode Python
- 对 HTTP 304 的理解
- http响应Last-Modified和ETag
- 利用ETag缓存优化请求
- 自己刷Leetcode的笔记:Longest Palindromic Substring
- C#中判断某软件是否已安装
- C# 关闭其他程序窗口、进程
- C# 强制关闭当前程序进程(完全Kill掉不留痕迹)
- Merge Sorted Array Leetcode Python