leetcode----86. Partition List

链接:

https://leetcode.com/problems/partition-list/

大意:

给定一个链表head和一个整数x,要求链表中所有值小于x的节点都在值大于等于x节点的左边,且需保证同侧的节点相对顺序不变。例子:

思路:

用两个队列small和big,分别存储原链表中值比x小的节点的值以及值大于等于x的节点的值。然后将small元素依次出队,用于设置链表中对应节点的值;待small遍历完成后,对big执行同样操作。

代码:

class Solution {
    public ListNode partition(ListNode head, int x) {
        if (head == null || head.next == null)
            return head;
        ListNode h = head;
        LinkedList<Integer> small = new LinkedList<>(), big = new LinkedList<>();
        while (h != null) {
            if (h.val < x)
                small.addLast(h.val);
            else 
                big.addLast(h.val);
            h = h.next;
        }
        h = head;
        Iterator<Integer> it = small.iterator();
        while (it.hasNext()) {
            h.val = it.next();
            h = h.next;
        }
        it = big.iterator();
        while (it.hasNext()) {
            h.val = it.next();
            h = h.next;
        }
        return head;
    }
}

结果:

结论:

菜的抠脚... 时间复杂度O(n) 空间复杂度O(n)。如果要优化的话 应该是从空间复杂度下手

最佳:

参考链接:https://leetcode.com/problems/partition-list/discuss/269507/java-solution-beats-100-simple-idea

主要思想:将原链表拆分成两个链表small和large,small中的元素为原链表中值比x小的节点,large中的元素为原链表中值大于等于x的节点。之后再将small的尾与large的头连接即可(...四天不写,手就生了还是人就笨了...)

class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode small = new ListNode(0);
        ListNode large = new ListNode(0);
        ListNode cur_small = small;
        ListNode cur_large = large;
        ListNode cur = head;
        while (cur != null) {
            if (cur.val < x) {
                cur_small.next = new ListNode(cur.val);
                cur_small = cur_small.next;
            } else {
                cur_large.next = new ListNode(cur.val);
                cur_large = cur_large.next;
            }
            cur = cur.next;
        }
        cur_small.next = large.next;
        return small.next;
    }
}

 

 

猜你喜欢

转载自blog.csdn.net/smart_ferry/article/details/89082463