624.Maximum Distance in Arrays --找数组中的最大差值
2017-07-05 11:27
531 查看
Given
from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers
be their absolute difference
Example 1:
这道题是找二维数组中的最大差值,其中所选取的整数a和b要来自不同的子数组,并且子数组中的整数是按升序排好的,所以每个子数组的第一个元素是最小的,最后一个元素是最大的,只需要比较每个子数组中的第一个即可找到最小值,比较每个子数组中的第二个即可找到最大值。但是因为整个二维数组的最大值和最小值可能来自相同的子数组,所以用一个变量res来控制,起初res赋值为0,因为差值的绝对值最小为0,然后求当前子数组中的最大值和之前所有子数组的最小值的差的绝对值,并用res记录,再求当前子数组中的最小值和之前所有子数组中的最值的差的绝对值,用res记录。这样保证了既取得最大值,并且所用的整数来自不同的子数组。代码如下:
marrays, 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
aand
bto
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.
这道题是找二维数组中的最大差值,其中所选取的整数a和b要来自不同的子数组,并且子数组中的整数是按升序排好的,所以每个子数组的第一个元素是最小的,最后一个元素是最大的,只需要比较每个子数组中的第一个即可找到最小值,比较每个子数组中的第二个即可找到最大值。但是因为整个二维数组的最大值和最小值可能来自相同的子数组,所以用一个变量res来控制,起初res赋值为0,因为差值的绝对值最小为0,然后求当前子数组中的最大值和之前所有子数组的最小值的差的绝对值,并用res记录,再求当前子数组中的最小值和之前所有子数组中的最值的差的绝对值,用res记录。这样保证了既取得最大值,并且所用的整数来自不同的子数组。代码如下:
int res = 0; int min = arrays[0][0]; int max = arrays[0][arrays[0].length-1]; for(int i=1;i<arrays.length;i++){ res = Math.max(res, Math.abs(arrays[i][arrays[i].length-1]-min)); res = Math.max(res, Math.abs(max-arrays[i][0])); min = Math.min(min,arrays[i][0]); max = Math.max(max, arrays[i][arrays[i].length-1]); } return res;
相关文章推荐
- LeetCode 624. Maximum Distance in Arrays (在数组中的最大距离)$
- [LeetCode] 624. Maximum Distance in Arrays 数组中的最大距离
- [LeetCode] Maximum Distance in Arrays 数组中的最大距离
- JavaScript实现-找出多个数组中的最大数-Return Largest Numbers in Arrays
- FCC算法:六、找出多个数组中的最大数--Return Largest Numbers in Arrays
- Maximum Distance in Arrays (第十七周 数组)
- LeetCode-624:Maximum Distance in Arrays (多数组找元素最大距离)
- [LeetCode] 624.Maximum Distance in Arrays
- 数组左边减去右边数值的最大差值
- 股票最大收益问题及数组最大差值问题
- java关于ArrayList动态数组与静态数组Arrays-元素比较输出最大最小值的使用例子
- Maximum Gap 寻找数组中排序后相邻两个数的最大差值,桶排序,O(n)
- 【编程习题★★★☆☆】寻找数组中元素间最大差值
- 找出数组中两段不相交的子数组,使其差值最大
- [算法]数组排序之后相邻数的最大差值
- BAT面试题 - 找一个无序实数数组中的最大差值
- 数组左边减去右边数值的最大差值
- 如果给定一个数组arr[0,...N-1],要求找出相邻两个数的最大差值
- 求一个数组中满足一定条件的两个元素的最大差值