题解 | #牛群的身高排序#

牛群的身高排序

https://www.nowcoder.com/practice/9ce3d60e478744c09768d1aa256bfdb5?tpId=354&tqId=10594759&ru=/exam/oj/ta&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D354

知识点:

小顶堆

解题思路:

遍历链表,将其放入小顶堆排序,在依次pop出即可

语言:

Golang

package main

import "container/heap"

import . "nc_tools"

/*
 * type ListNode struct{
 *   Val int
 *   Next *ListNode
 * }
 */

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param head ListNode类
 * @return ListNode类
 */
type MyHeap []*ListNode

func (h MyHeap) Less(a, b int) bool  { return h[a].Val < h[b].Val }
func (h MyHeap) Swap(a, b int)       { h[a], h[b] = h[b], h[a] }
func (h MyHeap) Len() int            { return len(h) }
func (h *MyHeap) Push(x interface{}) { *h = append(*h, x.(*ListNode)) }
func (h *MyHeap) Pop() interface{} {
	n := len(*h)
	ans := (*h)[n-1]
	*h = (*h)[:n-1]
	return ans
}
func sortList(head *ListNode) *ListNode {
	// write code here
	h := MyHeap{}
	heap.Init(&h)
	cur := head
	for cur != nil {
		heap.Push(&h, cur)
		cur = cur.Next
	}
	newHead := &ListNode{}
	cur = newHead
	for len(h) > 0 {
		cur.Next = heap.Pop(&h).(*ListNode)
        cur = cur.Next
	}
	cur.Next =nil
	return newHead.Next
}

全部评论

相关推荐

Java转测开第一人:这种就是饼 把应届当廉价劳动力用完然后丢掉
你觉得今年秋招难吗
点赞 评论 收藏
分享
10-14 21:00
门头沟学院 Java
吃花椒的狸猫:这个人说的倒是实话,特别是小公司,一个实习生哪里来的那么多要求
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务