LeetCode 624. Maximum Distance in Arrays (在数组中的最大距离)$
Given m
arrays, and each array is sorted in ascending order. Now you can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers a
and b
to be their absolute difference |a-b|
. Your task is to find the maximum distance.
Example 1:
Input: [[1,2,3], [4,5], [1,2,3]] Output: 4 Explanation: One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array.
Note:
- Each given array will have at least 1 number. There will be at least two non-empty arrays.
- The total number of the integers in all the
m
arrays will be in the range of [2, 10000]. - The integers in the
m
arrays will be in the range of [-10000, 10000].
题目标签:Array
题目给了我们一个 2d array,让我们求2个数字之间的最大差值。2个数字不能来自于同一行。
一开始想了一种方法,因为所有的array 都是 排序过的,那么只要在所有的array 的第一个数字里,找到一个min;在最后一个数字里,找到一个max,相减就是最大距离。
但是这样,有可能出现一种情况,就是2个数字来自于同一行。不符合要求。那么这样的话,只要多维护一个min2, 和max2, 还有minRowNum 和 maxRowNum就可以了,当min 和max 的row num是相等的话,比较max - min2 和 max2 - min就可以。
通过是没有问题,但是不够简洁。
下面这种方法更简洁。
设一个 maxDistance, min 和max。
为了避免2个数字来自于同一行,我们只要先设定max 和 min 是第一行的数字。对于后面的每一行的 tempMax 和tempMin, 只要在 max - tempMin 和 tempMax - min 里取大的那一个 和 maxDistance 比较一下,留下大的。
这样的话,每一次maxDistance 的2个数字,都是来自于不同行的。
Java Solution:
Runtime beats 97.61%
完成日期:10/15/2017
关键词:Array
关键点:利用排序的array,取第一个数字和最后一个数字 维护min ,max,和maxDistance
1 class Solution 2 { 3 public int maxDistance(List<List<Integer>> arrays) 4 { 5 int min = arrays.get(0).get(0); 6 int max = arrays.get(0).get(arrays.get(0).size() - 1); 7 int maxDistance = Integer.MIN_VALUE; 8 9 for(int i=1; i<arrays.size(); i++) 10 { 11 int tempMin = arrays.get(i).get(0); 12 int tempMax = arrays.get(i).get(arrays.get(i).size() - 1); 13 14 maxDistance = Math.max(maxDistance, Math.max(max - tempMin, tempMax - min)); 15 16 min = Math.min(min, tempMin); 17 max = Math.max(max, tempMax); 18 } 19 20 return maxDistance; 21 } 22 }
参考资料:
https://discuss.leetcode.com/topic/92859/java-solution-min-and-max
LeetCode 题目列表 - LeetCode Questions List
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· 软件产品开发中常见的10个问题及处理方法
· Vite CVE-2025-30208 安全漏洞
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· MQ 如何保证数据一致性?