最小区间问题

最小区间问题作者:Grey原文地址:最小区间问题题目描述LeetCode632.最小区间思路准备一个数据结构publicstaticclassNode{publicintvalue

最小区间问题

作者:Grey

原文地址:最小区间问题

题目描述

LeetCode 632. 最小区间

思路

准备一个数据结构

    public static class Node {        public int value;// 值是多少        public int position;// 在链表的哪个位置上        public int bucket; // 在哪个链表上        public Node(int v, int p, int b) {            value = v;            position = p;            bucket = b;        }    }

对链表中的每个元素都可以做这个数据结构的封装,其中value表示这个节点的值,position表示这个节点在链表中的哪个位置,bucket表示这个节点在哪个链表上。

准备一个有序表,有序表根据值来组织,值小的排在前面,如果值一样,按照链表顺序排;

首先将每个链表头节点都加入这个有序表,然后从有序表中获取第一个元素(最小元素)和最后一个元素(最大元素),这两个元素的区间,一定覆盖所有链表中的至少一个位置的数;

接下来看是否可以收窄区间,每次将有序表的头节点弹出,然后看这个弹出节点所在的链表的下一个位置是否有值,如果有,加入有序表,然后弹出有序表的头位置数据和尾位置数据,看下这个区间是否变的更窄,如此往复。直到某次弹出的值所在的链表已经无数据可加。

完整代码如下:

    public static class Node {        public int value;// 值是多少        public int position;// 在链表的哪个位置上        public int bucket; // 在哪个链表上        public Node(int v, int p, int b) {            value = v;            position = p;            bucket = b;        }    }    public static int[] smallestRange(List<List<Integer>> nums) {        if (nums == null) {            return null;        }        if (nums.size() == 1) {            if (nums.get(0).size() > 0) {                return new int[]{nums.get(0).get(0), nums.get(0).get(0)};            } else {                return null;            }        }        TreeSet<Node> set = new TreeSet<>((o1, o2) -> o1.value != o2.value ? o1.value - o2.value : o1.bucket - o2.bucket);        int i = 0;        for (List<Integer> list : nums) {            set.add(new Node(list.get(0), 0, i));            i++;        }        Node min = set.pollFirst();        Node max = set.last();        int[] result = {min.value, max.value};        while (min.position + 1 < nums.get(min.bucket).size()) {            set.add(new Node(nums.get(min.bucket).get(min.position + 1), min.position + 1, min.bucket));            min = set.pollFirst();            max = set.last();            result = minRange(result, new int[]{min.value, max.value});        }        return result;    }    public static int[] minRange(int[] a, int[] b) {        if (a[1] - a[0] > b[1] - b[0]) {            return b;        } else if (a[1] - a[0] < b[1] - b[0]) {            return a;        }        return a[0] > b[0] ? b : a;    }

更多

算法和数据结构笔记

本站部分文章来自网络或用户投稿,如无特殊说明或标注,均为本站原创发布。涉及资源下载的,本站旨在共享仅供大家学习与参考,如您想商用请获取官网版权,如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
开发者

【跟着大佬学JavaScript】之节流

2025-5-28 8:45:45

开发者

shell查询prometheus数据

2025-5-28 8:57:16

搜索