您的位置:首页 > 其它

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: