javascript解力扣面试题 02.04. 分割链表

面试题 02.04. 分割链表

题目

面试题 02.04. 分割链表
给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。

你不需要 保留 每个分区中各节点的初始相对位置。

示例 1:

输入:head = [1,4,3,2,5,2], x = 3
输出:[1,2,2,4,3,5]
示例 2:

输入:head = [2,1], x = 2
输出:[1,2]
 
提示:

链表中节点的数目在范围 [0, 200]-100 <= Node.val <= 100
-200 <= x <= 200

解法

var partition = function(head, x) {
    
    
    // 解法1:时间O(n),空间O(1),
    // 新建dummy指向head,把小于x的插入在dummy之后,
    // 注意排除head小于x的情况,不然会出现head指向自己
    // 执行用时:76 ms, 在所有 JavaScript 提交中击败了66.05%的用户
    // 内存消耗:38.9 MB, 在所有 JavaScript 提交中击败了97.53%的用户
    let smaller = head, dummy = new ListNode(), pre = dummy;
    dummy.next = head;
    while (smaller) {
    
    
        // console.log(smaller.val);
        if (smaller.val < x && smaller !== head) {
    
    
            let tmp = smaller.next;
            pre.next = smaller.next;
            smaller.next = dummy.next;
            dummy.next = smaller;
            smaller = tmp;
        }
        else {
    
    
            pre = smaller;
            smaller = smaller.next;
        }
    }
    return dummy.next;

    // 解法2:两个指针分别收集小于x和大于等于x的两个子链
    // 执行用时:72 ms, 在所有 JavaScript 提交中击败了84.57%的用户
    // 内存消耗:39 MB, 在所有 JavaScript 提交中击败了90.74%的用户
    let small = new ListNode(0), big = new ListNode(0), smallHead = small, bigHead = big;
    while (head) {
    
    
        if (head.val < x) {
    
    
            small.next = head;
            small = small.next;
        }
        else {
    
    
            big.next = head;
            big = big.next;
        }
        head = head.next;
    }
    small.next = bigHead.next;
    big.next = null;
    return smallHead.next;
};

解法二图解

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44495869/article/details/121576818