LeetCode--86. Partition List

题目链接:https://leetcode.com/problems/partition-list/

题意清晰,类似于快排中的partition操作,只是pivot是给定的,而不是链表中的元素。

思路一:遍历整个链表,用两个ArrayList分别存储小于x的节点和大于等于x的节点,存储的过程中改变节点的指向以形成两个链表,最后将这两个链表连在一起。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode partition(ListNode head, int x) {
        if(head==null || head.next==null)
            return head;
        ArrayList less=new ArrayList<>();
        ArrayList equalgreater=new ArrayList<>();
        
        ListNode p=head;
        while(p!=null)
        {
            if(p.val0)
                    less.get(n-1).next=p;
                less.add(p);
            }
            else
            {
                int n=equalgreater.size();
                if(n>0)
                    equalgreater.get(n-1).next=p;
                equalgreater.add(p);
            }
                
            p=p.next;
        }

        if(less.size()==0)
            return equalgreater.get(0);
        else if(equalgreater.size()==0)
            return less.get(0);
        else
        {
            less.get(less.size()-1).next=equalgreater.get(0);
            equalgreater.get(equalgreater.size()-1).next=null;
            return less.get(0);
        }
    }
}

O(n)的时间和空间复杂度,效率很一般,beat 35%。

思路二:Solutions里的双指针解法跟思路一本质上是一致的,代码如下:

class Solution {
    public ListNode partition(ListNode head, int x) {

        ListNode before_head = new ListNode(0);
        ListNode before = before_head;
        ListNode after_head = new ListNode(0);
        ListNode after = after_head;

        while (head != null) {

            if (head.val < x) {
                before.next = head;
                before = before.next;
            } else {

                after.next = head;
                after = after.next;
            }

            head = head.next;
        }

        after.next = null;
        before.next = after_head.next;
        return before_head.next;
    }
}

 

你可能感兴趣的:(LeetCode--86. Partition List)