前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 148 Sort List

LeetCode 148 Sort List

作者头像
ShenduCC
发布2019-03-15 14:40:47
3480
发布2019-03-15 14:40:47
举报
文章被收录于专栏:算法修养算法修养

LeetCode 148 Sort List

排序,

我使用了三种排序:

手写快排: 48ms

C++模板快排: 48ms

堆排序:52ms

c++:

代码语言:javascript
复制
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */



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



int a[100005];
int pos = 0;


void inserts(int x)
{
     a[++pos]=x;
     int j=pos;
     while(j>1)
     {
         if(a[j]<a[j/2])
         {
             swap(a[j],a[j/2]);
             j=j/2;
         }
         else
             break;
     }     
}

void removes()
{
    swap(a[pos],a[1]);
    int j=1;
          pos--;
    while(j<pos)
    {
        if(j*2>pos) break;
        
        if(j*2+1>pos)
        {
            if(a[j]>a[j*2])
            {
                swap(a[j],a[j*2]);
                j=j*2;
                continue;
            }
            else
                break;
        }
        
        if(j*2+1<=pos)
        {
            if(a[j*2]<a[j*2+1]&&a[j]>a[j*2])
            { 
               swap(a[j],a[j*2]);
                j=j*2; 
                continue;
            }
            if(a[j*2]>=a[j*2+1]&&a[j]>a[j*2+1])
            {
                swap(a[j],a[j*2+1]);
                j=j*2+1;
                continue;
            }
            else
                break;
        }

    }

}
    
    void quickSort(int l,int r)
    {
        if(r<=l)return;
        int start = l+1;
        int end = r;
        int pos=l;
        while(true)
        {
            while(a[pos]>a[end]&&end>l)
            {
                end--;
            }
            while(a[pos]<a[start]&&start<=r)
            {
                start++;
            }
            if(end<start) break;
            swap(a[start],a[end]);
            start++;
            end--;
        }
        
        swap(a[pos],a[end]);
        
        quickSort(l,end-1);
        quickSort(end+1,r);  
            
    }



ListNode* sortList(ListNode* head) {
   ListNode* list = new ListNode(0);
    if(head==NULL) return NULL;
    
   ListNode* temp = head;
   int  tag=0;
    while(temp!=NULL)
    {
       a[tag++]=temp->val;
        temp = temp->next;
    }
    quickSort(0,tag-1);
    ListNode* term = list;
    int tag2=tag-1;
    while(tag2>=0)
    {
        term->val = a[tag2--];
        if(tag2==-1)
            break;
        term->next = new ListNode(0);
        term = term->next;
    }
    
    return list;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-03-10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档