leetcode Sort List

没想到什么好办法,要将O(ologn)时间里完成,我先遍历一遍将链表存储到数组里,再对数组进行排序,排序方法写了快排和归并的,过是能过,但是时间要140ms,最快的就是直接对链表进行归并排序,第一次写比较难受,用快慢指针来分成两个链表,具体思想还是和数组的归并排序一样。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

void merge(int A[],int L1,int R1,int L2,int R2){
    int i = L1, j = R2; // i指向A[L1] j指向A[L2]
    int temp[100000], Index = 0;
    while (i <= R1 && j<=R2) {
        if (A[i] <= A[j])
            temp[Index++] = A[i++];
        else
            temp[Index++] = A[j++];
    }
    while (i <= R1) temp[Index++] = A[i++];
    while (j <= R2) temp[Index++] = A[j++];
    for (int i =0; i<Index; i++)
        A[L1 + i] = temp[i];
}

void merge_sort(int A[],int left,int right){
    if (left < right){
        int mid = (left+right) / 2;
        merge_sort(A, left, mid);
        merge_sort(A, mid+1, right);
        merge(A, left, mid,mid+1,right);
    }
}
int Partition(int A[],int left,int right){
    int temp = A[left];
    while (left < right) {
        while (left < right && A[right] > temp)
            right--;
        A[left] = A[right];
        while (left <right && A[left] <= temp)
            left++;
        A[right] = A[left];
    }
    A[left] = temp;
    return left;
}

void quick_sort(int A[],int left,int right){
    if (left < right) {
        int pos = Partition(A, left, right);
        quick_sort(A, left, pos-1);
        quick_sort(A, pos+1, right);
    }
}


struct ListNode* sortList(struct ListNode* head) {
    if(!head || !head->next)
        return head;
    int data[100000];
    int index = 0; // the length of the list
    struct ListNode *current = head;
    while(current){
        data[index++] = current->val;
        current = current->next;
    }
    quick_sort(data,0,index-1);
    current = head;
    index = 0;
    while(current){
        current->val = data[index++];
        current = current->next;
    }
    return head;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值