关闭

【Leetcode】Partition List

235人阅读 评论(0) 收藏 举报
分类:

题目链接: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;
	}



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:535884次
    • 积分:8370
    • 等级:
    • 排名:第2624名
    • 原创:305篇
    • 转载:6篇
    • 译文:0篇
    • 评论:35条
    博客专栏
    文章分类
    最新评论