Leetcode题目之求解数组之间的最大距离

来源:互联网 发布:可以看央视的网络电视 编辑:程序博客网 时间:2024/06/05 04:39

打算从今天开始开辟一个LeetCode专栏,收集并讲解LeetCode网站的一些题目。

今天的题目是LeetCode第37期的第一个题目,比较简单。

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].
这是题目要求,大致意思就是给出m个数组,这些数组已经按照升序排列,求出数组之间的最大距离。

public class Solution {    public int maxDistance(List<List<Integer>> arrays) {        int result = Integer.MIN_VALUE;        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++)        {            result = Math.max(result,Math.abs(arrays.get(i).get(0)-max));            result = Math.max(result,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 result;    }}

采用List来存储一些List,遍历之即可