解题思路:
这道题我将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;
}
}
运行结果: