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

推荐订阅源

Microsoft Azure Blog
Microsoft Azure Blog
WordPress大学
WordPress大学
Google DeepMind News
Google DeepMind News
美团技术团队
大猫的无限游戏
大猫的无限游戏
H
Help Net Security
小众软件
小众软件
aimingoo的专栏
aimingoo的专栏
博客园 - 聂微东
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
M
MIT News - Artificial intelligence
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - Franky
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Microsoft Security Blog
Microsoft Security Blog
F
Fortinet All Blogs
A
About on SuperTechFans
Recent Announcements
Recent Announcements
D
Docker
Vercel News
Vercel News
Engineering at Meta
Engineering at Meta
腾讯CDC
Martin Fowler
Martin Fowler
阮一峰的网络日志
阮一峰的网络日志

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
        }
    }

}