1. 程式人生 > >【Leetcode】86.(Medium)Partition List

【Leetcode】86.(Medium)Partition List

解題思路:
這道題我將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;
	}
}

執行結果:
在這裡插入圖片描述