LeetCode-624:Maximum Distance in Arrays (多数组找元素最大距离)

来源:互联网 发布:淘宝短信营销话术 编辑:程序博客网 时间:2024/06/07 03:20

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: 4Explanation: 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)
阅读全文
0 0
原创粉丝点击