Leetcode-86. Partition List

来源:互联网 发布:淘宝一淘入口 编辑:程序博客网 时间:2024/05/23 18:37

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

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的数,然后把后面所有小于的移到前面就可以了。Your runtime beats 5.10% of java submissions.

public class Solution {    public ListNode partition(ListNode head, int x) {        if(head == null) return head;        if(head.next == null) return head;        boolean isExits = false;        ListNode headPoint = new ListNode(0);        headPoint.next = head;        ListNode searchNode = head;        ListNode bigNode = null, preNode = headPoint;        searchNode = headPoint;        while(searchNode != null){            if(searchNode.next != null && searchNode.next.val >= x && bigNode == null) {                preNode = searchNode; bigNode = searchNode.next;                isExits = true; break;            }            searchNode = searchNode.next;        }            if(isExits){            ListNode preSearchNode = preNode;            searchNode = bigNode;            while(searchNode != null){                if(searchNode.val < x){                    preSearchNode.next = searchNode.next;                    preNode.next = searchNode;                    searchNode.next = bigNode;                    preNode = preNode.next;                    searchNode = preSearchNode.next;                }else{                    preSearchNode = searchNode;                    searchNode = searchNode.next;                }            }        }        return headPoint.next;    }}





0 0
原创粉丝点击