[leetcode]Sort List

来源:互联网 发布:windows防火墙开关 编辑:程序博客网 时间:2024/06/15 22:04

Sort List

 

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

此方法利用快速排序思想,但因测试数据种类小数量大,而超时

class Solution {public:    //快速排序,算法导论版, 从前向后进行的    ListNode* partition(ListNode *head, ListNode *tail){    ListNode *rear = head->next;    ListNode *front = head;    int x = head->val;    for(ListNode *ptr = rear; ptr != tail; ptr = ptr->next){    if(ptr->val <= x){    swap(ptr->val, front->next->val);    front = front->next;    }    }    swap(head->val, front->val);    return front;    }    void quicksort(ListNode *head, ListNode *tail){    if(head != tail){    ListNode *mid = partition(head, tail);    quicksort(head, mid);    quicksort(mid->next, tail);    }    }    ListNode *sortList(ListNode *head) {    // IMPORTANT: Please reset any member data you declared, as    // the same Solution instance will be reused for each test case.    quicksort(head, NULL);    return head;    }};


利用了stl源码库中的map(以红黑树做为实现结构)

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *sortList(ListNode *head) {        if(NULL == head) return NULL;                map<int, int> mii;        ListNode *ptr = head;        while(ptr){            mii[ptr->val]++;            ptr = ptr->next;        }        ptr = head;        while(ptr){            for(map<int, int>::iterator itor = mii.begin(); itor != mii.end(); itor++){                for(int i = 0; i < itor->second; i++){                    ptr->val = itor->first;                    ptr = ptr->next;                 }            }        }                return head;    }};

0 0
原创粉丝点击