最大数

166 阅读1分钟

题目描述

leetcode-cn.com/problems/la…

分析

使用堆排序,总是把大的字符放到前面

算法

过程

手写一个堆(省略)

Heap compareFn

着重讲一下 compareFn,两个字符串连接起来之后所表示的数字的大于小,被决定于两字符串 a, b 的连接方式是 a + b, 还是 b + a,又因为要的是最大值,因此我们的 compareFn 对比的是 a + b < b + a

将所有数字序列化并放入堆中

此处调用的是 heapinsert

构建返回值

不断 extract

代码

/**
 * @param {number[]} nums
 * @return {string}
 */
var largestNumber = function(nums) {
    
};

class Heap {
    constructor(compareFn) {
        this.heap = []
        this.compareFn = compareFn
    }
    
    getLeftIndex(index) {
        return index * 2 + 1
    }
    
    getRightIndex(index) {
        return index * 2 + 2
    }
    
    getParentIndex(index) {
        return Math.floor((index - 1) / 2)
    }
    
    size() {
        return this.heap.length
    }
    
    isEmpty() {
        return this.size() === 0
    }
    
    swap(parent, index) {
        const arr = this.heap;
        ;[arr[parent], arr[index]] = [arr[index], arr[parent]]
    }
    
    insert(value) {
        const index = this.heap.length
        this.heap.push(value)
        this.siftUp(index)
    }
    
    siftUp(index) {
        let parent = this.getParentIndex(index)
        
        while (index > 0 && this.compareFn(this.heap[parent], this.heap[index])) {
            this.swap(parent, index)
            index = parent
            parent = this.getParentIndex(index)
        }
    }
    
    extract() {
        if (this.isEmpty()) return
        if (this.size() === 1) return this.heap.pop()
        const removedItem = this.heap[0]
        this.heap[0] = this.heap.pop()
        this.siftDown(0)
        
        return removedItem
    }
    
    siftDown(index) {
        let element = index
        const left = this.getLeftIndex(index)
        const right = this.getRightIndex(index)
        
        if (index < this.size() && this.compareFn(this.heap[element], this.heap[left])) {
            element = left
        }
        
        if (index < this.size() && this.compareFn(this.heap[element], this.heap[right])) {
            element = right
        }
        
        if (index !== element) {
            this.swap(element, index)
            this.siftDown(element)
        }
    }
    
    top() {
        return this.heap[0]
    }
}