【Leetcode】Partition List

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

题目:

Given 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.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

思路:

先把两类结点保存,然后统一链接。时间复杂度O(n),空间复杂度O(n)。

算法:

	public ListNode partition(ListNode head, int x) {
		ListNode p = head, h1 = null, r2 = null, r1 = null, h2 = null;
		List<Integer> l1 = new ArrayList<Integer>();
		List<Integer> l2 = new ArrayList<Integer>();
		while (p != null) {
			if (p.val < x) {
				l1.add(p.val);
			} else {
				l2.add(p.val);
			}
			p = p.next;
		}
		Iterator<Integer> i1 = l1.iterator();
		while (i1.hasNext()) {
			if (h1 == null) {
				h1 = new ListNode((Integer) i1.next());
				r1 = h1;
			} else {
				r1.next = new ListNode((Integer) i1.next());
				r1 = r1.next;
			}
		}
		Iterator<Integer> i2 = l2.iterator();
		while (i2.hasNext()) {
			if (h2 == null) {
				h2 = new ListNode((Integer) i2.next());
				r2 = h2;
			} else {
				r2.next = new ListNode((Integer) i2.next());
				r2 = r2.next;
			}
		}
		if (r1 != null) {
			r1.next = h2;
			head = h1;
		} else {
			head = h2;
		}

		return head;
	}



思路二:

将两类各自结点链接,最后合并。时间复杂度O(n),空间复杂度O(1)

算法二:

	public ListNode partition(ListNode head, int x) {
		ListNode lessHead = new ListNode(0);
		ListNode greaterHead = new ListNode(0);
		ListNode node = head, less = lessHead, greater = greaterHead;
		while (node != null) {
			ListNode next = node.next;
			if (node.val < x) {
				less.next = node;
				less = less.next;
				less.next = null;
			} else {
				greater.next = node;
				greater = greater.next;
				greater.next = null;
			}
			node = next;
		}
		less.next = greaterHead.next;
		return lessHead.next;
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值