zoukankan      html  css  js  c++  java
  • [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].

    数组列表中的最大距离。题意是给了M个数组,每个数组都是有序的,现在请你在数组中找出两个元素,是的他们的差的绝对值最大。这两个元素需要来自两个不同的子数组。

    这道题不涉及算法,不过注意因为要找的元素一定要来自两个不同的子数组,所以你需要比较这么几组元素的差值以得出要求的最大的绝对值。

    • 当前子数组的最小元素和上一个子数组的最大元素
    • 当前子数组的最大元素和上一个子数组的最小元素

    时间O(n)

    空间O(1)

    Java实现

     1 class Solution {
     2     public int maxDistance(List<List<Integer>> arrays) {
     3         int min = arrays.get(0).get(0);
     4         int max = arrays.get(0).get(arrays.get(0).size() - 1);
     5         int res = Integer.MIN_VALUE;
     6         for (int i = 1; i < arrays.size(); i++) {
     7             res = Math.max(res, Math.abs(arrays.get(i).get(0) - max));
     8             res = Math.max(res, Math.abs(arrays.get(i).get(arrays.get(i).size() - 1) - min));
     9             max = Math.max(max, arrays.get(i).get(arrays.get(i).size() - 1));
    10             min = Math.min(min, arrays.get(i).get(0));
    11         }
    12         return res;
    13     }
    14 }

    LeetCode 题目总结

  • 相关阅读:
    阿里在线笔试总结
    JAVA断言使用
    小心人员中的薄弱点
    Ubuntu 12.04.4 LTS下linphone-android编译记录
    Java基础:异常的限制
    Java基础:小知识点
    js正则表达式中和\
    Maven管理下Struts、Hibernate编译过程中配置文件缺失导致的“No result defined for action”和getSession()发生“NullPointerException”的解决办法
    Java基础:final关键字
    Java基础:复用类
  • 原文地址:https://www.cnblogs.com/cnoodle/p/13759713.html
Copyright © 2011-2022 走看看