波波老师您好,听完5-2后,尝试做了您布置的练习,发现86题partition并没有想象中的简单。在经历了将近40分钟的思考,编写,分情况讨论,print调试,和Debug,终于得到了accepted并且运行速度也超过了其他程序的100%。
但是看了Solution给出的答案后,发现自己的答案过于冗长,而且也不是最佳的逻辑,感觉很有挫败感。
想请问波波老师,首先,究竟什么才是正确的刷题方法?其次,是否掌握了正确的方法后,就能在短时间内一次性写出像solution一样的最佳答案呢?
附上自己写的86题答案,供其他同学一起学习进步:)
public static ListNode partition(ListNode head, int x) {
if(head == null)
return null;
//分情况讨论,看list的第一个数值是否小于x
//如果小于x,则标记位置(对应变量s),并找到第一个大于x的节点作为pivot(对应变量st)
//之后通过不断改变原有指针,先将所有小于x的节点串联,再讲所有大于x的节点串联
//最后连接两部分
if(head.val < x){
ListNode s = head;
//System.out.println("s now is "+s.val);
while(s.next != null && s.next.val < x){
s = s.next;
//System.out.println("s now is "+s.val);
}
if(s.next == null){
return head;
}
ListNode st = s.next;
//System.out.println("st now is "+st.val);
ListNode b = s.next;
//System.out.println("b now is "+b.val);
if(b.next == null){
return head;
}
//到此为止,s, st, b都有了
ListNode cur = b;
//System.out.println("cur now is "+cur.val);
while(cur.next != null){
if(cur.next.val < x){
s.next = cur.next;
s = s.next;
//System.out.println("s now is "+s.val);
}
else{
//System.out.println(cur.val);
//System.out.println(cur.next.val);
b.next = cur.next;
b = b.next;
//System.out.println("b now is "+b.val);
}
cur = cur.next;
//System.out.println("cur now is "+cur.val);
}
s.next = st;
b.next = null;
}
else{
ListNode b = head;
ListNode st = b;
while(b.next != null && b.next.val >= x){
b = b.next;
}
if(b.next == null){
return head;
}
ListNode s = b.next;
head = s;
if(s.next == null){
s.next = st;
b.next = null;
return head;
}
//到此为止,s, st, b都有了
ListNode cur = s;
while(cur.next != null){
if(cur.next.val >= x){
b.next = cur.next;
b = b.next;
}
else{
//System.out.println(cur.val);
//System.out.println(cur.next.val);
s.next = cur.next;
s = s.next;
}
cur = cur.next;
}
s.next = st;
b.next = null;
}
return head;
}