【Leetcode】Partition List (Swap)
来源:互联网 发布:python node.js 配合 编辑:程序博客网 时间:2024/06/05 09:25
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
.
这道题是一道分割的题,要求把比x小的元素放到x的前面,而且相对顺序不能变
这个时候我们采用双指针法
runner1用于寻找最后一个比x小得元素,这里作为插入点(分割点)
runner2用于寻找应该插到插入点之后的元素
所以这里会出现三种情况
情况1: runner2的元素小于x,这个时候如果runner1和runner2指向同一个元素,说明还没有找到分割点,所以两个指针继续往前走就行了。
情况2: runner2的元素小于x,这个时候如果runner1和runner2指向不同的元素,说明runner1已经走到了分割点前,而runner2.next就是应该被插到分割点前。把runner2.next插入到分割点前就ok
情况3: runner2的元素大于x, 这个时候找到了分割点,只移动runner2就可以了。直到runner2.next小于分割点。然后按照情况2来操作就可以了
情况1和情况2:
if (runner2.next.val < x) {if (runner1 == runner2) {runner1 = runner1.next;runner2 = runner2.next;} else {ListNode insert = runner2.next;ListNode next = insert.next;insert.next = runner1.next;runner1.next = insert;runner2.next = next;runner1 = runner1.next;}}
情况3:
elserunner2 = runner2.next;
完整代码如下
public ListNode partition(ListNode head, int x) {if (head == null)return head;ListNode helper = new ListNode(0);helper.next = head;ListNode runner1 = helper;ListNode runner2 = helper;while (runner2 != null && runner2.next != null) {if (runner2.next.val < x) {if (runner1 == runner2) {runner1 = runner1.next;runner2 = runner2.next;} else {ListNode insert = runner2.next;ListNode next = insert.next;insert.next = runner1.next;runner1.next = insert;runner2.next = next;runner1 = runner1.next;}} elserunner2 = runner2.next;}return helper.next;}
0 0
- 【Leetcode】Partition List (Swap)
- 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
- [LeetCode] Partition List
- LeetCode 86: Partition List
- LeetCode:Partition List
- oracle备份报error 12541错解决方法
- 网址的链接
- 如何 读取 设置 - 开发者选项 - 不保留活动 的状态
- VIM+Gnome-Terminal配色方案
- Hibernate注解方式的二级缓存
- 【Leetcode】Partition List (Swap)
- Coldfusion视频教程,中文版的
- X Shell 4配色方案[Solarized Dark]
- jdk6原生态webservice
- 【总结】Java与字符编码问题详谈
- swift之单例模式
- QAction系列详解
- Visual.C#.2010从入门到精通].(Visual.C#.2010.Step.By.Step)读书笔记 数组、集合(九)
- java获取系统编码