【Leetcode】86.(Medium)Partition List

本文详细解析了LeetCode上的一道经典链表分区题目,提供了两种解决方案:一种是通过转换链表为ArrayList来实现,另一种是采用双指针技巧,后者时间效率更优。文章深入探讨了每种方法的实现细节及潜在的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解题思路:
这道题我将list转化为了ArrayList来做
基本思路是先将链表转化为ArrayList,然后找到第一个大于等于x的数字,并记下位置flag。然后从后向前,如果是小于x的数就插入到flag的位置。比较耗时的地方是每次将数字插入到flag的位置时,ArrayList会将所有flag之后的数字后移一位。
这道题还有一种做法是设置双指针,时间效率是线性的:
https://leetcode.com/problems/partition-list/discuss/193969/Java-beats-100-(0ms)-%2B-explanation


提交代码1:转化为成ArrayList来做

class Solution {
	public ListNode partition(ListNode head, int x) {
		// turn the lists to nums
		List<Integer> nums = new ArrayList<Integer>();
		ListNode p = head;
		while (p != null) {
			nums.add(p.val);
			if (p != null)
				p = p.next;
		}

		// find the first num bigger than x
		int flag, tmp, cnt = 0;
		for (flag = 0; flag < nums.size(); flag++)
			if (nums.get(flag) >= x)
				break;

		for (int i = nums.size() - 1; i >= flag + cnt; i--) {
			if (nums.get(i) < x) {
				tmp = nums.get(i);
				nums.remove(i);
				nums.add(flag, tmp);
			//	System.out.println(nums);
				i++;
				cnt++;
			}
		}
		// System.out.println(nums);

		// turn nums to list
		ListNode newHead;
		if (nums.size() == 0)
			newHead = null;
		else
			newHead = new ListNode(nums.get(0));
		p = newHead;
		for (int i = 1; i < nums.size(); i++) {
			ListNode newNode = new ListNode(nums.get(i));
			p.next = newNode;
			p = p.next;
			p.next = null;
		}
		return newHead;
	}
}

运行结果:
在这里插入图片描述


提交代码2:转化为成ArrayList来做

class Solution {
	public ListNode partition(ListNode head, int x) {
        if(head==null||head.next==null) return head;
		ListNode head1=new ListNode(-1);
		ListNode head2=new ListNode(-1);
		head1.next=null;head2.next=null;
		ListNode p=head,pTmp=head.next,p1=head1,p2=head2;
		
		while(p!=null) {
			if(p.val<x) {
				p1.next=p;p1=p1.next;p1.next=null;
			}else {
				p2.next=p;p2=p2.next;p2.next=null;
			}
			p=pTmp;
			if(p!=null)	pTmp=p.next;
		}
		p1.next=head2.next;
		return head1.next;
	}
}

运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值