您的位置:首页 > 其它

[Leetcode] 624. Maximum Distance in Arrays 解题报告

2018-01-07 12:27 656 查看
题目

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 t
4000
he range of [-10000, 10000].
思路

如果arrays公有n行,那么我们提供如下两个时间复杂度的版本:

1、O(nlogn):首先统计每一行的最大数和最小数,然后分别进行排序。最后对每一行的最小数字,在最大数数组里面顺序查找,如果发现不是同一列,则记录最大差值,并跳出。最后返回全局最大差值即可。由于涉及排序,所以时间复杂度是O(nlogn),但是由于max_values是有序的,所以后面的两重循环中的内层循环的时间复杂度实际上是O(1)。

2、O(n):在顺序扫描每一行的过程中,维护截止目前已扫描行中的最小数和最大数,然后在当前行中更新最大差值即可。之所以可以这么做,是由每行数据的有序性,我们可以知道最大差值一定是某一行的最大值与另一行的最小值的差值(可以采用反证法证明)。

代码

1、O(nlogn):

class Solution {
public:
int maxDistance(vector<vector<int>>& arrays) {
vector<pair<int, int>> max_values; // (value, row_index)
vector<pair<int, int>> min_values;
for (int r = 0; r < arrays.size(); ++r) {
max_values.push_back(make_pair(arrays[r].back(), r));
min_values.push_back(make_pair(arrays[r][0], r));
}
sort(max_values.begin(), max_values.end(), greater<pair<int, int>>());
sort(min_values.begin(), min_values.end(), less<pair<int, int>>());
int ret = 0;
for (int i = 0; i < min_values.size(); ++i) {
for (int j = 0; j < max_values.size(); ++j) {
if (min_values[i].second != max_values[j].second) {
ret = max(ret, max_values[j].first - min_values[i].first);
break;
}
}
}
return ret;
}
};
2、O(n):

class Solution {
public:
int maxDistance(vector<vector<int>>& arrays) {
if (arrays.size() == 0) {
return 0;
}
int left = arrays[0][0], right = arrays[0].back(), ans = 0;
for(int i = 1; i < arrays.size(); i++) {
int temp_ans = max(abs(arrays[i][0] - right), abs(arrays[i].back() - left));
ans = max(ans, temp_ans);
left = min(left, arrays[i][0]), right = max(right, arrays[i].back());
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: