您的位置 首页 JAVA(2017)

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:

  1. Each given array will have at least 1 number. There will be at least two non-empty arrays.
  2. The total number of the integers in all the m arrays will be in the range of [2, 10000].
  3. The integers in the m arrays will be in the range of [-10000, 10000].
public class Solution {
    public int maxDistance(List<List<Integer>> arrays) {
        int min = arrays.get(0).get(0);
        int max = arrays.get(0).get(arrays.get(0).size() -1);
        int res = 0;
        for(int i=1;i<arrays.size();i++){
            if(Math.abs(max-arrays.get(i).get(0))>res){
                res = Math.abs(max-arrays.get(i).get(0));
            }
            if(Math.abs(arrays.get(i).get(arrays.get(i).size() -1) - min) > res){
                res = Math.abs(arrays.get(i).get(arrays.get(i).size() -1) - min);
            }
            if(arrays.get(i).get(0)<min){
                min = arrays.get(i).get(0);
            }
            if(arrays.get(i).get(arrays.get(i).size() -1)>max){
                max = arrays.get(i).get(arrays.get(i).size() -1);
            }
        }
        return res;
    }
}
看完了?留个评分呗?
[0人评了分,平均: 0/5]

本站原创文章皆遵循“署名-非商业性使用-相同方式共享 3.0 (CC BY-NC-SA 3.0)”。转载请保留以下标注:

原文来源:《LeetCode – 624. Maximum Distance in Arrays》

发表评论

邮箱地址不会被公开。

返回顶部