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].

 


 

题目标签:Array

  题目给了我们一个 2d array,让我们求2个数字之间的最大差值。2个数字不能来自于同一行。

  一开始想了一种方法,因为所有的array 都是 排序过的,那么只要在所有的array 的第一个数字里,找到一个min;在最后一个数字里,找到一个max,相减就是最大距离。

  但是这样,有可能出现一种情况,就是2个数字来自于同一行。不符合要求。那么这样的话,只要多维护一个min2, 和max2, 还有minRowNum 和 maxRowNum就可以了,当min 和max 的row num是相等的话,比较max - min2 和 max2 - min就可以。

  通过是没有问题,但是不够简洁。

 

  下面这种方法更简洁。

  设一个 maxDistance, min 和max。

  为了避免2个数字来自于同一行,我们只要先设定max 和 min 是第一行的数字。对于后面的每一行的 tempMax 和tempMin,  只要在 max - tempMin 和 tempMax - min 里取大的那一个 和 maxDistance 比较一下,留下大的。

  这样的话,每一次maxDistance 的2个数字,都是来自于不同行的。

 

 

Java Solution:

Runtime beats 97.61% 

完成日期:10/15/2017

关键词:Array

关键点:利用排序的array,取第一个数字和最后一个数字 维护min ,max,和maxDistance

 1 class Solution 
 2 {
 3     public int maxDistance(List<List<Integer>> arrays) 
 4     {
 5         int min = arrays.get(0).get(0);
 6         int max = arrays.get(0).get(arrays.get(0).size() - 1);
 7         int maxDistance = Integer.MIN_VALUE;
 8         
 9         for(int i=1; i<arrays.size(); i++)
10         {
11             int tempMin = arrays.get(i).get(0);
12             int tempMax = arrays.get(i).get(arrays.get(i).size() - 1);
13             
14             maxDistance = Math.max(maxDistance, Math.max(max - tempMin, tempMax - min));
15             
16             min = Math.min(min, tempMin);
17             max = Math.max(max, tempMax);
18         }
19         
20         return maxDistance;
21     }
22 }

参考资料:

https://discuss.leetcode.com/topic/92859/java-solution-min-and-max

 

LeetCode 题目列表 - LeetCode Questions List

 

posted @ 2017-10-16 11:20  Jimmy_Cheng  阅读(223)  评论(0编辑  收藏  举报