Sort List LeetCode
来源:互联网 发布:python双击闪退 编辑:程序博客网 时间:2024/06/13 23:21
public ListNode sortList(ListNode head) {if (head == null || head.next == null) {return head;}int len=0;int i=0;ListNode p=head;while(p!=null){ len++; p=p.next;}int[] arr=new int[len+1];p=head;while(p!=null){arr[i++]=p.val;p=p.next;}sort(arr,0,len+1);head.val=arr[0];p=head.next;for(int j=1;j<len+1;j++){p.val=arr[j];p=p.next;}return head;}private void sort(int[] arr, int index, int len) { for(int i=len>>1;i>=0;i--){ buildMaxHeap(arr,i,len); } for(int i=len-1;i>=0;i--){ int temp=arr[0]; arr[0]=arr[i]; arr[i]=temp; buildMaxHeap(arr,0,i); }}private void buildMaxHeap(int[] arr, int i, int len) { int l = left(arr,i); int r = righ(arr,i); int largest=i; if(l<len&&arr[i]<arr[l]){ largest=l; } if(r<len&&arr[r]>arr[largest]){ largest=r; } if(largest!=i){ int temp=arr[largest]; arr[largest]=arr[i]; arr[i]=temp; buildMaxHeap(arr,largest,len); }}private int righ(int[] arr, int i) {return 2*i+2;}private int left(int[] arr, int i) {return 2*i+1;}
题目链接:点击打开链接
思想:把链表转化为数组来存储链表每一个节点的值,然后对数组进行堆排序,排序好了之后,把数组中的值重新放到以前的链表中
0 0
- [leetcode][list][sort] Sort List
- Insertion Sort List | leetcode
- Leetcode: Insertion Sort List
- [LeetCode] Insertion Sort List
- Leetcode: Insertion Sort List
- Leetcode: Sort List
- Sort List | leetcode
- leetcode-Sort List
- leetcode-Insertion Sort List
- LeetCode题解:Sort List
- leetcode 134: Sort List
- [LeetCode]Sort List
- [LeetCode]Insertion Sort List
- [LeetCode] Sort List
- 【LeetCode】Insertion Sort List
- leetCode - Sort List
- LeetCode | Insertion Sort List
- LeetCode - Insertion Sort List
- Activity 视图相关类 4.4
- UML九类图
- Android调试之tombstone信息的分析
- 双链表&链表合并&多项式相加算法
- CodeFroces 445B DZY Loves Chemistry
- Sort List LeetCode
- iOS音频播放 (一):概述 转
- poj 2540 && uva 10084 Hotter Colder(半平面交)
- 取数游戏_签到积分
- hdu 1010 Tempter of the Bone
- poj 1015 Jury Compromise dp
- 黑马程序员_集合框架工具类
- sizeof小结
- 解决"Windows系统自带共享代理软件导致的断网问题"