题目描述:
LeetCode 624. 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].
题目大意:
给定一组数组arrays,各数组递增有序,求不同数组之间最小值、最大值之间差值绝对值的最大值。
解题思路:
解法I 一趟遍历 时间复杂度O(n),n为arrays的长度
Java代码:
public class Solution {
public int maxDistance(List<List<Integer>> arrays) {
int ans = 0;
int max = arrays.get(0).get(arrays.get(0).size() - 1);
int min = arrays.get(0).get(0);
for (int i = 1; i < arrays.size(); i++) {
ans = Math.max(ans, Math.abs(arrays.get(i).get(0) - max));
ans = Math.max(ans, Math.abs(arrays.get(i).get(arrays.get(i).size() - 1) - min));
max = Math.max(max, arrays.get(i).get(arrays.get(i).size() - 1));
min = Math.min(min, arrays.get(i).get(0));
}
return ans;
}
}
解法II TreeMap(红黑树) 时间复杂度O(n * log(n)),n为arrays的长度
构造红黑树maxMap, minMap分别存储arrays各数组的最大值和最小值。 遍历arrays,记当前数组为array,其最小值min = array[0], 最大值max = array[array.length - 1] 分别将max和min从maxMap,minMap中移除 利用maxMap.lastKey() - min,max - minMap.firstKey()更新答案 然后将max和min添加回maxMap与minMap
Java代码:
public class Solution {
public int maxDistance(List<List<Integer>> arrays) {
TreeMap<Integer, Integer> maxMap = new TreeMap<>();
TreeMap<Integer, Integer> minMap = new TreeMap<>();
for (List<Integer> list : arrays) {
int min = list.get(0), max = list.get(list.size() - 1);
maxMap.put(max, maxMap.getOrDefault(max, 0) + 1);
minMap.put(min, minMap.getOrDefault(min, 0) + 1);
}
int ans = 0;
for (List<Integer> list : arrays) {
int min = list.get(0), max = list.get(list.size() - 1);
if (maxMap.put(max, maxMap.get(max) - 1) == 1) {
maxMap.remove(max);
}
if (minMap.put(min, minMap.get(min) - 1) == 1) {
minMap.remove(min);
}
ans = Math.max(ans, maxMap.lastKey() - min);
ans = Math.max(ans, max - minMap.firstKey());
maxMap.put(max, maxMap.getOrDefault(max, 0) + 1);
minMap.put(min, minMap.getOrDefault(min, 0) + 1);
}
return ans;
}
}
本文链接:http://bookshadow.com/weblog/2017/06/18/leetcode-maximum-distance-in-arrays/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。