返回介绍

solution / 0000-0099 / 0086.Partition List / README_EN

发布于 2024-06-17 01:04:39 字数 6103 浏览 0 评论 0 收藏 0

86. Partition List

中文文档

Description

Given the head of 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.

 

Example 1:

Input: head = [1,4,3,2,5,2], x = 3
Output: [1,2,2,4,3,5]

Example 2:

Input: head = [2,1], x = 2
Output: [1,2]

 

Constraints:

  • The number of nodes in the list is in the range [0, 200].
  • -100 <= Node.val <= 100
  • -200 <= x <= 200

Solutions

Solution 1: Simulation

We create two linked lists, one to store nodes less than $x$, and the other to store nodes greater than or equal to $x$. Then we concatenate them.

The time complexity is $O(n)$, where $n$ is the length of the original linked list. The space complexity is $O(1)$.

# Definition for singly-linked list.
# class ListNode:
#   def __init__(self, val=0, next=None):
#     self.val = val
#     self.next = next
class Solution:
  def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
    d1, d2 = ListNode(), ListNode()
    t1, t2 = d1, d2
    while head:
      if head.val < x:
        t1.next = head
        t1 = t1.next
      else:
        t2.next = head
        t2 = t2.next
      head = head.next
    t1.next = d2.next
    t2.next = None
    return d1.next
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *   int val;
 *   ListNode next;
 *   ListNode() {}
 *   ListNode(int val) { this.val = val; }
 *   ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
  public ListNode partition(ListNode head, int x) {
    ListNode d1 = new ListNode();
    ListNode d2 = new ListNode();
    ListNode t1 = d1, t2 = d2;
    while (head != null) {
      if (head.val < x) {
        t1.next = head;
        t1 = t1.next;
      } else {
        t2.next = head;
        t2 = t2.next;
      }
      head = head.next;
    }
    t1.next = d2.next;
    t2.next = null;
    return d1.next;
  }
}
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *   int val;
 *   ListNode *next;
 *   ListNode() : val(0), next(nullptr) {}
 *   ListNode(int x) : val(x), next(nullptr) {}
 *   ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
  ListNode* partition(ListNode* head, int x) {
    ListNode* d1 = new ListNode();
    ListNode* d2 = new ListNode();
    ListNode* t1 = d1;
    ListNode* t2 = d2;
    while (head) {
      if (head->val < x) {
        t1->next = head;
        t1 = t1->next;
      } else {
        t2->next = head;
        t2 = t2->next;
      }
      head = head->next;
    }
    t1->next = d2->next;
    t2->next = nullptr;
    return d1->next;
  }
};
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *   Val int
 *   Next *ListNode
 * }
 */
func partition(head *ListNode, x int) *ListNode {
  d1, d2 := &ListNode{}, &ListNode{}
  t1, t2 := d1, d2
  for head != nil {
    if head.Val < x {
      t1.Next = head
      t1 = t1.Next
    } else {
      t2.Next = head
      t2 = t2.Next
    }
    head = head.Next
  }
  t1.Next = d2.Next
  t2.Next = nil
  return d1.Next
}
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
//   pub val: i32,
//   pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
//   #[inline]
//   fn new(val: i32) -> Self {
//   ListNode {
//     next: None,
//     val
//   }
//   }
// }
impl Solution {
  pub fn partition(head: Option<Box<ListNode>>, x: i32) -> Option<Box<ListNode>> {
    let mut head = head;
    let mut d1 = Some(Box::new(ListNode::new(0)));
    let mut d2 = Some(Box::new(ListNode::new(0)));
    let (mut t1, mut t2) = (&mut d1, &mut d2);
    while let Some(mut node) = head {
      head = node.next.take();
      if node.val < x {
        t1.as_mut().unwrap().next = Some(node);
        t1 = &mut t1.as_mut().unwrap().next;
      } else {
        t2.as_mut().unwrap().next = Some(node);
        t2 = &mut t2.as_mut().unwrap().next;
      }
    }
    t1.as_mut().unwrap().next = d2.unwrap().next;
    d1.unwrap().next
  }
}
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *   this.val = (val===undefined ? 0 : val)
 *   this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} x
 * @return {ListNode}
 */
var partition = function (head, x) {
  const d1 = new ListNode();
  const d2 = new ListNode();
  let t1 = d1,
    t2 = d2;
  while (head) {
    if (head.val < x) {
      t1.next = head;
      t1 = t1.next;
    } else {
      t2.next = head;
      t2 = t2.next;
    }
    head = head.next;
  }
  t1.next = d2.next;
  t2.next = null;
  return d1.next;
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文