1334. 阈值距离内邻居最少的城市

2023-09-21 11:25:59

原题链接:

1334. 阈值距离内邻居最少的城市

https://leetcode.cn/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/solutions

完成情况:

在这里插入图片描述

解题思路:

  给你一个边数组 edges,其中 edges[i] = [fromi, toi, weighti] 代表 fromi 和 toi 两个城市之间的双向加权边
    距离阈值是一个整数 distanceThreshold。
    返回能通过某些路径到达其他城市数目最少、且路径距离 最大 为 distanceThreshold 的城市。如果有多个这样的城市,则返回编号最大的城市。

    返回要求:
        距离路径最大,且相连城市最少,然后同情况下编号最大的城市。

    他的邻居指的不是相邻,而是只要在<=最大 为 distanceThreshold 的城市

    解法:
        对每一个节点,去计算满足在<=最大 为 distanceThreshold结点内的邻居数量,然后挨个节点去判断谁的邻居最少,并且节点编号能够更大。

    题目就转化成了对所有节点,计算到其他结点的最短路径       Dijkstra算法  &&  Floyd算法

参考代码:

Dijkstra

package LeetCode中等题02;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class __1334阈值距离内邻居最少的城市__Dijkstra{
    /**
     *
     * @param n
     * @param edges
     * @param distanceThreshold
     * @return
     */
    public int findTheCity(int n, int[][] edges, int distanceThreshold) {
/**      给你一个边数组 edges,其中 edges[i] = [fromi, toi, weighti] 代表 fromi 和 toi 两个城市之间的双向加权边
        距离阈值是一个整数 distanceThreshold。
        返回能通过某些路径到达其他城市数目最少、且路径距离 最大 为 distanceThreshold 的城市。如果有多个这样的城市,则返回编号最大的城市。

        返回要求:
            距离路径最大,且相连城市最少,然后同情况下编号最大的城市。

        他的邻居指的不是相邻,而是只要在<=最大 为 distanceThreshold 的城市

        解法:
            对每一个节点,去计算满足在<=最大 为 distanceThreshold结点内的邻居数量,然后挨个节点去判断谁的邻居最少,并且节点编号能够更大。

        题目就转化成了对所有节点,计算到其他结点的最短路径       Dijkstra算法  &&  Floyd算法
 */
        List<int []>  adjacentArray [] = new List[n];
        for (int i = 0;i<n;i++){
            adjacentArray[i] = new ArrayList<int[]>();
        }
        for (int edge [] : edges){
            int cityA = edge[0],cityB = edge[1],weigth = edge[2];
            adjacentArray[cityA].add(new int[]{cityB,weigth});
            adjacentArray[cityB].add(new int[]{cityA,weigth});
        }
        int leastCity = Integer.MIN_VALUE,leastNeightbors = Integer.MAX_VALUE;
        for (int i=n-1;i>=0;i--){
            int neighbors = Dijkstra(adjacentArray,i,distanceThreshold);
            if (leastNeightbors > neighbors){
                leastCity = i;
                leastNeightbors = neighbors;
            }
        }
        return leastCity;
    }

    /**
     *
     * @param adjacentArray
     * @param sourceFrom
     * @param distanceThreshold
     * @return
     */
    private int Dijkstra(List<int[]>[] adjacentArray, int sourceFrom, int distanceThreshold) {
        int n = adjacentArray.length;
        int distancces [] = new int[n];
        Arrays.fill(distancces,Integer.MAX_VALUE / 2);
        distancces[sourceFrom] = 0;
        boolean [] visited = new boolean[n];
        for (int i = 0;i<n;i++){
            int curr = -1;
            for (int j=0;j<n;j++){
                if (!visited[j] && (curr < 0 || distancces[curr] > distancces[j])){
                    curr = j;
                }
            }
            visited[curr] = true;
            for (int [] adjacent: adjacentArray[curr]){
                int next = adjacent[0],weight = adjacent[1];
                distancces[next] = Math.min(distancces[next],distancces[curr] + weight);
            }
        }
        int neighbors = 0;
        for (int i = 0;i<n;i++){
            if (i == sourceFrom){
                continue;
            }
            if (distancces[i] <= distanceThreshold){
                neighbors++;
            }
        }
        return neighbors;
    }
}

Dijkstra_小顶堆

package LeetCode中等题02;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;

public class __1334阈值距离内邻居最少的城市__Dijkstra_小顶堆 {
    /**

     * @param n
     * @param edges
     * @param distanceThreshold
     * @return
     */
    public int findTheCity(int n, int[][] edges, int distanceThreshold) {
        List<int []>  adjacentArray [] = new List[n];
        for (int i = 0;i<n;i++){
            adjacentArray[i] = new ArrayList<int[]>();
        }
        for (int edge [] : edges){
            int cityA = edge[0],cityB = edge[1],weigth = edge[2];
            adjacentArray[cityA].add(new int[]{cityB,weigth});
            adjacentArray[cityB].add(new int[]{cityA,weigth});
        }
        int leastCity = Integer.MIN_VALUE,leastNeightbors = Integer.MAX_VALUE;
        for (int i=n-1;i>=0;i--){
            int neighbors = Dijkstra(adjacentArray,i,distanceThreshold);
            if (leastNeightbors > neighbors){
                leastCity = i;
                leastNeightbors = neighbors;
            }
        }
        return leastCity;
    }

    /**
     *
     * @param adjacentArray
     * @param sourceFrom
     * @param distanceThreshold
     * @return
     */
    private int Dijkstra(List<int[]>[] adjacentArray, int sourceFrom, int distanceThreshold) {
        int n = adjacentArray.length;
        int distancces [] = new int[n];
        Arrays.fill(distancces,Integer.MAX_VALUE );
        distancces[sourceFrom] = 0;
        //小顶堆,是基于队列
        //Deque实现stack,PriorityQueue实现queue
        PriorityQueue<int []> pQueue = new PriorityQueue<int []>((a,b) -> a[1] - b[1]); //直接插入比较规则
        pQueue.offer(new int[]{sourceFrom,0});
        while (!pQueue.isEmpty()){
            int pair[] = pQueue.poll();
            int curr = pair[0],distancce = pair[1];
            for (int [] adjancet : adjacentArray[curr]){
                int next =  adjancet[0],weight = adjancet[1];
                if (distancces[next] > distancce + weight){
                    distancces[next] = distancce + weight;
                    pQueue.offer(new int[]{next,distancces[next]});
                }
            }
        }
        int neightbors = 0;
        for (int i = 0;i<n;i++){
            if (i == sourceFrom){
                continue;
            }
            if (distancces[i] <= distanceThreshold){
                neightbors++;
            }
        }
        return neightbors;
    }
}

Floyd_martix方法

package LeetCode中等题02;

import java.util.Arrays;

public class __1334阈值距离内邻居最少的城市__Floyd_martix方法 {
    /**
     *
     * @param n
     * @param edges
     * @param distanceThreshold
     * @return
     */
    public int findTheCity(int n, int[][] edges, int distanceThreshold) {
        int [][] matrix = new int[n][n];
        for (int i = 0;i<n;i++){
            Arrays.fill(matrix[i],Integer.MAX_VALUE / 2);
        }
        for (int edge [] : edges){
            int cityA = edge[0],cityB = edge[1],weigth = edge[2];
            matrix[cityA][cityB] = matrix[cityB][cityA] = weigth;
        }
        for (int k = 0;k<n;k++){
            for (int i = 0;i<n;i++){
                for (int j = 0;j<n;j++){
                    matrix[i][j] = Math.min(matrix[i][j],matrix[i][k] + matrix[k][j]);
                }
            }
        }
        int leastCity = -1,leastNeightbors = Integer.MAX_VALUE;
        for (int i = n-1;i>=0;i--){
            int neightbors = countNeughtbors_Floyd(matrix,i,distanceThreshold);
            if (leastNeightbors > neightbors){
                leastCity = i;
                leastNeightbors = neightbors;
            }
        }
        return leastCity;
    }

    /**
     *
     * @param matrix
     * @param i
     * @param distanceThreshold
     * @return
     */
    private int countNeughtbors_Floyd(int[][] matrix, int sourceFrom, int distanceThreshold) {
        int neightbors = 0;
        int n = matrix.length;
        for (int i = 0;i<n;i++){
            if (i == sourceFrom){
                continue;
            }
            if (matrix[sourceFrom][i] <= distanceThreshold){
                neightbors++;
            }
        }
        return neightbors;
    }
}

更多推荐

七、【漏洞复现】YApi接口管理平台远程代码执行漏洞

七、【漏洞复现】YApi接口管理平台远程代码执行漏洞7.1、漏洞原理若YApi对外开放注册功能,攻击者可在注册并登录后,通过构造特殊的请求执行任意代码,接管服务器。7.2、影响版本YApi<=V1.92All7.3、指纹识别1.有注册登陆主页2.使用指纹识别类平台识别。7.4、漏洞复现1.注册账号2.新建项目-名称随意

uniapp引入小程序原生插件

怎么在uniapp中使用微信小程序原生插件,以收钱吧支付插件为例1、在manifest.json里的mp-weixin中增加插件配置"mp-weixin":{"appid":"你的小程序appid","setting":{"urlCheck":false},"usingComponents":true,//在下面配置插

1.9python基础语法——运算符

1)算数运算符运算符描述实例+加1+1输出结果为2-减1-1输出结果为0*乘2*2输出结果为4/除10/2输出结果为5//整除9//4输出结果为2%取余9%4输出结果为1**指数2***4输出结果为16,即2*222()小括号小括号用来提高运算优先级,即(1+2)*3输出结果为9注意:混合运算优先级顺序:()高于**高

Laravel5使用box/spout扩展,大文件导出CSV文件

一、背景早期开发的系统,使用laravel框架,版本V5.4,项目经理导出3年的数据,由于数据量较大,浏览器卡死。一次性无法导出,某位程序员告知按月去导出,之后在拼凑,这。。搁谁受的了,我担心投诉,加个班优化下。二、优化方案导出数据的Sql,对应创建索引,提高查询速度查询结果集使用chunk()方法拆分较小集合使用bo

Hive 的权限管理

目录​编辑一、Hive权限简介1.1hive中的用户与组1.1.1用户1.1.2组1.1.3角色1.2使用场景1.2.1hivecli1.2.2hiveserver21.2.3hcatalogapi1.3权限模型1.3.1StorageBasedAuthorizationintheMetastoreServer1.3.

竞赛选题 基于机器视觉的火车票识别系统

文章目录0前言1课题意义课题难点:2实现方法2.1图像预处理2.2字符分割2.3字符识别部分实现代码3实现效果最后0前言🔥优质竞赛项目系列,今天要分享的是基于机器视觉的火车票识别系统该项目较为新颖,适合作为竞赛课题方向,学长非常推荐!🧿更多资料,项目分享:https://gitee.com/dancheng-sen

MySQL数据库查缺补漏——基础篇

MySQL数据库查缺补漏-基础篇基础篇netstartmysql80[服务名]netstopmysql80createdatabasepshdhxdefaultcharsetutf8mb4;为什么不使用utf8?因为其字符占用三个字节,有四个字节的字符,所有需要设置为utf8mb4;数值类型:字符串类型:日期类型:用户

汽车自适应巡航系统车距控制策略研究

摘要:由于汽车自适应巡航控制系统的非线性和不确定性等问题,传统的非线性系统等效线性化方法难以满足系统的精度、稳定度和快速性的要求,因此提出了一种基于模糊控制理论的自适应巡航控制器的设计方法。通过对汽车距离差和相对速度的计算和推理,实时调整本车加速度,保证本车能够在一定的安全车距下跟随前车。通过在Matlab/Simul

虹科案例 | LIN/CAN总线汽车零部件测试方案

文章来源:虹科汽车电子点此阅读原文虹科的LIN/CAN总线汽车零部件测试方案是一款优秀的集成套装,基于Baby-LIN系列产品,帮助客户高效完成在测试、生产阶段车辆零部件质量、功能、控制等方面的检测工作。1、汽车零部件测试的重要性?汽车零部件的测试对于确保汽车的安全性、功能性和可靠性起着至关重要的作用。LIN/CAN通

驱动开发DAY4

驱动代码#include<linux/init.h>#include<linux/module.h>#include<linux/cdev.h>#include<linux/fs.h>#include<linux/device.h>#include<linux/uaccess.h>#include<linux/slab

【Pytest实战】Pytest+Allure+Jenkins自动化测试框架搭建

😄作者简介:小曾同学.com,一个致力于测试开发的博主⛽️,主要职责:测试开发、CI/CD如果文章知识点有错误的地方,还请大家指正,让我们一起学习,一起进步。😊座右铭:不想当开发的测试,不是一个好测试✌️。如果感觉博主的文章还不错的话,还请点赞、收藏哦!👍之前分享过Pytest基础知识,可参考Pytest实战专栏

热文推荐