LeetCode 148之Sort List的java题解
题目:
Sort a linked list in O(n log n) time using constant space complexity.
解答:
解题报告:就是对一个链表进行归并排序。
主要考察3个知识点,
知识点1:归并排序的整体思想
知识点2:找到一个链表的中间节点的方法
知识点3:合并两个已排好序的链表为一个新的有序链表
归并排序的基本思想是:找到链表的middle节点,然后递归对前半部分和后半部分分别进行归并排序,最后对两个以排好序的链表进行Merge。
代码:
寻找中间节点(用快慢指针):
public static ListNode getMiddleOfList(ListNode head) { ListNode slow=head; ListNode fast=head; while(fast.next!=null&&fast.next.next!=null) { slow=slow.next; fast=fast.next.next; } return slow; }
合并两个链表:
public static ListNode mergeTwoList(ListNode headA,ListNode headB) {
ListNode fakeNode=new ListNode(-1);
ListNode cur=fakeNode;
while(headA!=null&&headB!=null)
{
if(headA.val<=headB.val)
{
cur.next=headA;
headA=headA.next;
}
else {
cur.next=headB;
headB=headB.next;
}
cur=cur.next;
}
cur.next=headA==null?headB:headA;
return fakeNode.next;
}
归并排序主函数:
public static ListNode sortList(ListNode head) { if(head==null||head.next==null)//递归出口 当只有一个节点时就不再递归 return head; ListNode middle=getMiddleOfList(head); ListNode next=middle.next; middle.next=null;//把两个链表断开分为左边(包括middle)一半和右边一半 return mergeTwoList(sortList(head), sortList(next));}
leetcode255
/方法1
class Solution {
public boolean verifyPreorder(int[] arr) {
return check(arr, 0, arr.length-1);
}
public boolean check(int[] arr, int i, int j){
if(i>=j) return true;
int root = arr[i];
// k为右子树的开始下标,
int k=i+1;
while(k<=j && arr[k]<root) k++;
//验证右子树是否都>root
for(int m=k; m<=j; m++)
if(arr[m]<root) return false;
//如果根合格,看其左右子树是否合格
return check(arr,i+1,k-1) && check(arr, k, j);
}
}