Maximum Distance in Arrays (第十七周 数组)

给定多个升序数组,计算并返回两个不同数组中元素的最大绝对差值。一种有效策略是记录当前遍历到的最左和最右元素,遍历过程中不断更新这两个值,从而在遍历结束后得到最大距离。
摘要由CSDN通过智能技术生成

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:

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

算法思路

(1)找到m个数组之间的最大距离,题目本来是挺简单的,但是第一次交的时候超时了。
(2)原本的想法双重遍历数组,得到2个头元素的2个末元素,然后就可以计算出两个距离了,然后和历史的最大值进行比较,取三者当中的最大值。其实结果是对的,但是会超时。
(3)后来想了想,其实没有必要双重遍历,一重即可,即是 On 时间就可以了。因为最大的距离是源于一个数组的末元素与另一个数据的头元素的差。我们每次都记录最右的元素与最左的元素。然后遍历数组的时候,就可以更新最右和最左的元素了,然后就可以计算出最大的距离。

算法代码

class Solution {
public:
    int maxDistance(vector<vector<int> >& arrays) {
        int right = arrays[0][arrays[0].size() - 1];
        int left = arrays[0][0];
        int res = -9999;
        int len = arrays.size();
        for(int i = 1; i < len; i++){
            res = max(right - arrays[i][0], res);
            res = max(arrays[i][arrays[i].size() - 1] - left, res);
            left = min(left, arrays[i][0]);
            right = max(right, arrays[i][arrays[i].size() - 1]);
        }
        return res;
    }
};   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值