LeetCode-624:Maximum Distance in Arrays (多数组找元素最大距离)
来源:互联网 发布:淘宝短信营销话术 编辑:程序博客网 时间:2024/06/07 03:20
Question
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: 4Explanation: 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].
问题解析:
给定的多个(至少两个,且非空)按升序排序好的数组,从其中任意两个数组中各选择一个元素,计算两个元素的距离,找到最大距离。
Answer
Solution 1:
遍历记录最大值距离和最大值最小值即可。
- 注意不能选择同一个数组中的最大值和最小值;
- 因为题目中给出的条件是多个数组均已经拍排好序,所以可以将多个数组视为一个数组,数组中的一个元素由两个值组成:
arrays[i][0]
和arrays[i][i.length-1]
; - 遍历过程中需要保存每次计算的最大距离以及最大值和最小值;
- 注意距离要通过两个元素之交叉计算得出,这样可以避免同一个元素大小值计算的问题。
class Solution { public int maxDistance(List<List<Integer>> arrays) { int res = 0; int min = arrays.get(0).get(0); int max = arrays.get(0).get(arrays.get(0).size() - 1); for (int i = 1; i < arrays.size(); i++) { List<Integer> array = arrays.get(i); res = Math.max(Math.abs(min - array.get(array.size() - 1)), Math.max(Math.abs(array.get(0) - max), res)); min = Math.min(min, array.get(0)); max = Math.max(max, array.get(array.size() - 1)); } return res; }}
- 时间复杂度:O(n);空间复杂度:O(1)
阅读全文
0 0
- LeetCode-624:Maximum Distance in Arrays (多数组找元素最大距离)
- 624. Maximum Distance in Arrays 数组最大距离
- 624.Maximum Distance in Arrays --找数组中的最大差值
- Leetcode 624 Maximum Distance in Arrays
- leetcode-624. Maximum Distance in Arrays
- [leetcode]: 624. Maximum Distance in Arrays
- [LeetCode]624. Maximum Distance in Arrays
- [LeetCode]624. Maximum Distance in Arrays
- [LeetCode] 624.Maximum Distance in Arrays
- leetcode624: Maximum Distance in Arrays
- leetcode624. Maximum Distance in Arrays
- Python 刷题日记:LeetCode 624. Maximum Distance in Arrays
- Maximum Distance in Arrays (第十七周 数组)
- 566. Reshape the Matrix/624. Maximum Distance in Arrays/594. Longest Harmonious Subsequence
- [LeetCode] Maximum Subarray、Edit Distance
- leetcode:Edit Distance 编辑距离
- leetcode 编辑距离 Edit Distance
- 找最大元素
- JAVA_位运算符_含义
- 设计模式_21:中介者模式
- C++ complex类
- hcharts实现堆叠柱形图
- ORACLE_表空间_计算增加数据文件数量
- LeetCode-624:Maximum Distance in Arrays (多数组找元素最大距离)
- MapReduce--1--入门程序WordCount
- git reset如何回滚代码
- MyEclipse导入jquery-1.8.0.min.js等文件报错的解决方案 版权声明:本文为博主原创文章,未经博主允许不得转载。 MyEclipse导入jQuery-1.8.0.min.j
- leetcode 51
- Android两个控件叠在一起,如何让被挡住的控件显示出来
- java线程之生产者与消费者模式
- 页面居中、响应式布局的总结
- 应用保活终极总结(二):Android6.0及以上的保活实践