LeetCode-624:Maximum Distance in Arrays (多数组找元素最大距离)
2017-10-23 12:55
501 查看
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: 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].
问题解析:
给定的多个(至少两个,且非空)按升序排序好的数组,从其中任意两个数组中各选择一个元素,计算两个元素的距离,找到最大距离。
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)
相关文章推荐
- [LeetCode] Maximum Distance in Arrays 数组中的最大距离
- [LeetCode] 624. Maximum Distance in Arrays 数组中的最大距离
- leetcode624: Maximum Distance in Arrays
- Leetcode 624 Maximum Distance in Arrays
- LeetCode 624. Maximum Distance in Arrays (在数组中的最大距离)$
- LeetCode Maximum Distance in Arrays
- LeetCode解题思路之Maximum Distance in Arrays
- [LeetCode]624. Maximum Distance in Arrays
- [LeetCode] Maximum XOR of Two Numbers in an Array 数组中异或值最大的两个数字
- [LeetCode] 774. Minimize Max Distance to Gas Station 最小化加油站间的最大距离
- LeetCode-628:Maximum Product of Three Numbers (数组三元素最大乘积)
- leetcode-624. Maximum Distance in Arrays
- [Leetcode] 624. Maximum Distance in Arrays 解题报告
- Maximum Distance in Arrays
- [LeetCode] 624.Maximum Distance in Arrays
- LeetCode-643:Maximum Average Subarray I (k个元素的最大子数组)
- Python 刷题日记:LeetCode 624. Maximum Distance in Arrays
- 624.Maximum Distance in Arrays --找数组中的最大差值
- Maximum Distance in Arrays (第十七周 数组)
- [leetcode]: 624. Maximum Distance in Arrays