327. Count of Range Sum

Posted apanda009

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了327. Count of Range Sum相关的知识,希望对你有一定的参考价值。

Sort a linked list in O(n log n) time using constant space complexity.

这道题跟Insertion Sort List类似,要求我们用O(nlogn)算法对链表进行排序,但是并没有要求用哪一种排序算法,我们可以使用归并排序,快速排序,堆排序等满足要求的方法来实现。对于这道题比较容易想到的是归并排序,因为我们已经做过Merge Two Sorted Lists,这是归并排序的一个subroutine。剩下我们需要做的就是每次找到中点,然后对于左右进行递归,最后用Merge Two Sorted Lists把他们合并起来。代码如下:

public ListNode sortList(ListNode head) {  
    return mergeSort(head);  
}  
private ListNode mergeSort(ListNode head)  
{  
    if(head == null || head.next == null)  
        return head;  
    ListNode walker = head;  
    ListNode runner = head;  
    while(runner.next!=null && runner.next.next!=null)  
    {  
        walker = walker.next;  
        runner = runner.next.next;  
    }  
    ListNode head2 = walker.next;  
    walker.next = null;  
    ListNode head1 = head;  
    head1 = mergeSort(head1);  
    head2 = mergeSort(head2);  
    return merge(head1, head2);  
}  
private ListNode merge(ListNode head1, ListNode head2)  
{  
    ListNode helper = new ListNode(0);  
    helper.next = head1;  
    ListNode pre = helper;  
    while(head1!=null && head2!=null)  
    {  
        if(head1.val<head2.val)  
        {  
            head1 = head1.next;  
        }  
        else  
        {  
            ListNode next = head2.next;  
            head2.next = pre.next;  
            pre.next = head2;  
            head2 = next;  
        }  
        pre = pre.next;  
    }  
    if(head2!=null)  
    {  
        pre.next = head2;  
    }  
    return helper.next;  
}  

 walker.next = null; -->为了下次的分割, 

pre = pre.next;  --> 为了找到拼接的位置

链表的拼接, 先记住后面的节点, 先拼接后面的节点, 不然不好表示

 ListNode next = head2.next;  
 head2.next = pre.next;  
 pre.next = head2;   

以上是关于327. Count of Range Sum的主要内容,如果未能解决你的问题,请参考以下文章

327. Count of Range Sum

LeetCode 327. Count of Range Sum

Leetcode327: Count of Range Sum 范围和个数问题

[LeetCode]Count of Range Sum

[LeetCode] Count of Range Sum 区间和计数

938. Range Sum of BST