Maximum Distance in Arrays (第十七周 数组)
2017-06-24 12:17
295 查看
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].
算法思路
(1)找到m个数组之间的最大距离,题目本来是挺简单的,但是第一次交的时候超时了。(2)原本的想法双重遍历数组,得到2个头元素的2个末元素,然后就可以计算出两个距离了,然后和历史的最大值进行比较,取三者当中的最大值。其实结果是对的,但是会超时。
(3)后来想了想,其实没有必要双重遍历,一重即可,即是O(n)时间就可以了。因为最大的距离是源于一个数组的末元素与另一个数据的头元素的差。我们每次都记录最右的元素与最左的元素。然后遍历数组的时候,就可以更新最右和最左的元素了,然后就可以计算出最大的距离。
算法代码
class Solution { public: int maxDistance(vector<vector<int> >& arrays) { int right = arrays[0][arrays[0].size() - 1]; int left = arrays[0][0]; int res = -9999; int len = arrays.size(); for(int i = 1; i < len; i++){ res = max(right - arrays[i][0], res); res = max(arrays[i][arrays[i].size() - 1] - left, res); left = min(left, arrays[i][0]); right = max(right, arrays[i][arrays[i].size() - 1]); } return res; } };
相关文章推荐
- [LeetCode] Maximum Distance in Arrays 数组中的最大距离
- LeetCode Maximum Distance in Arrays
- LeetCode-624:Maximum Distance in Arrays (多数组找元素最大距离)
- LeetCode 624. Maximum Distance in Arrays (在数组中的最大距离)$
- leetcode624: Maximum Distance in Arrays
- Leetcode 624 Maximum Distance in Arrays
- Maximum Distance in Arrays
- [LeetCode] 624. Maximum Distance in Arrays 数组中的最大距离
- LeetCode解题思路之Maximum Distance in Arrays
- 624.Maximum Distance in Arrays --找数组中的最大差值
- [LeetCode] Maximum XOR of Two Numbers in an Array 数组中异或值最大的两个数字
- [leetcode]: 624. Maximum Distance in Arrays
- [Leetcode] 624. Maximum Distance in Arrays 解题报告
- 数组空间Given a sequence of numbers (or array).Find the maximum distance between all the same numbers.
- [LeetCode] 624.Maximum Distance in Arrays
- FCC算法:六、找出多个数组中的最大数--Return Largest Numbers in Arrays
- leetcode-624. Maximum Distance in Arrays
- Maximum Distance in Array
- JavaScript实现-找出多个数组中的最大数-Return Largest Numbers in Arrays
- 在排序数组中找到第k个元素 find the k-th element in two sorted arrays