惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
Docker
阮一峰的网络日志
阮一峰的网络日志
T
Tailwind CSS Blog
博客园 - 【当耐特】
量子位
博客园 - 叶小钗
有赞技术团队
有赞技术团队
Jina AI
Jina AI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - Franky
博客园 - 司徒正美
爱范儿
爱范儿
美团技术团队
小众软件
小众软件
酷 壳 – CoolShell
酷 壳 – CoolShell
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
V
V2EX
罗磊的独立博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Last Week in AI
Last Week in AI
Hugging Face - Blog
Hugging Face - Blog
I
InfoQ
D
DataBreaches.Net
宝玉的分享
宝玉的分享

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Thoughts on implementing a custom Priority Queue in TS
Arun Prakash Pandey · 2026-06-16 · via DEV Community

Arun Prakash Pandey

LC 1046

My two cents:

  1. Each push and pop requires a rearrangement of the existing elements, it's almost like the priority queue is a living organism which evolves / devolves it self to maintain the order of the elements.
  2. Swap, BubbleUp, & BubbleDown are the methods doing the main lifting. Here, swap is the simple swap operation
    const temp: T = this.heap[i];
    this.heap[i] = this.heap[j];
    this.heap[j] = temp

  3. The this.compare dependency injection is the soul of the code here. It is the same deciding factor which is used in sorting elements in an array. number < 0, number = 0 & number > 0
    where number is the result of a-b or b-a.

bubbleUp and bubbleDown ensure the rearrangement which is required to maintain the order of the elements,
bubbleDown refers to the Pop operation, and bubbleUp refers to the push operation. This is because how they are implemented in the custom heap inside the CustomPriorityQueue class.

Complexity

  • Time complexity: O(N * log(N)); explanation : Push, Pop has log(N) and Stones array traversal has N.
  • Space complexity: O(N) for additional priority queue.

Code

function lastStoneWeight(stones: number[]): number {
    const PQ = new CustomPriorityQueue<number>((a, b) => b-a);
    for (let i of stones) {
        PQ.push(i);
    }
    while(PQ.size() > 1){
        const y: number = PQ.pop();
        const x: number = PQ.pop();
        if(y>x){
            PQ.push(y-x);
        }
    }
    // console.log(PQ);
    return PQ.isEmpty() ? 0 : PQ.peak();
};

class CustomPriorityQueue<T> {
    private heap: T[] = [];
    private compare: ((a: T, b: T) => number);

    constructor(compare: (a: T, b: T) => number) {
        this.compare = compare
        // this.heap = [];
    }

    public size(): number {
        return this.heap.length
    }
    public isEmpty(): boolean {
        return this.size() === 0;
    }
    public peak(): T | undefined {
        return this.heap[0]
    }
    private swap(i: number, j: number): void {
        const temp: T = this.heap[i];
        this.heap[i] = this.heap[j];
        this.heap[j] = temp
    }
    public push(value: T): void {
        this.heap.push(value);
        this.bubbleUp(this.size() - 1);
    }
    private bubbleUp(index: number): void {
        while (index > 0) {
            let parentIndex: number = Math.floor((index - 1) / 2);
            if (this.compare(this.heap[parentIndex], this.heap[index]) < 0) break;
            this.swap(parentIndex, index);
            index = parentIndex
        }
    }
    public pop(): T | undefined {
        if (this.isEmpty()) return undefined;
        const top: T = this.heap[0];
        const bottom: T = this.heap.pop();
        if (!this.isEmpty() && bottom !== undefined) {
            this.heap[0] = bottom;
            this.bubbleDown(0);
        }
        return top;
    }
    private bubbleDown(index: number): void {
        const length: number = this.size();
        while (true) {
            let leftChildIndex: number = 2 * index + 1;
            let rightChildIndex: number = 2 * index + 2
            let indexOfSmallestOrLargest: number = index;

            if (leftChildIndex < length && this.compare(this.heap[leftChildIndex], this.heap[indexOfSmallestOrLargest]) < 0) {
                indexOfSmallestOrLargest = leftChildIndex;
            }
            if (rightChildIndex < length && this.compare(this.heap[rightChildIndex], this.heap[indexOfSmallestOrLargest]) < 0) {
                indexOfSmallestOrLargest = rightChildIndex;
            }
            if (indexOfSmallestOrLargest === index) break;

            this.swap(index, indexOfSmallestOrLargest);
            index = indexOfSmallestOrLargest
        }
    }

}