【Lintcode】1657. Operation Time

题目地址:

https://www.lintcode.com/problem/operation-time/description

给定两个数组 A A A B B B A A A代表某个文件, B B B代表 A A A文件的操作时间,求所有文件中,操作时间最大值和最小值之差最大的那个文件,对应的差。

用两个哈希表,一个记录每个文件的最长操作时间,另一个记录最短操作时间,然后做差再更新答案即可。代码如下:

import java.util.HashMap;
import java.util.Map;

public class Solution {
    /**
     * @param op: the operation
     * @param a: time of each operation
     * @return: the max sum
     */
    public int operationTime(int[] op, int[] a) {
        // Write your code here.
        Map<Integer, Integer> maxMap = new HashMap<>(), minMap = new HashMap<>();
    
        for (int i = 0; i < op.length; i++) {
            maxMap.put(op[i], Math.max(maxMap.getOrDefault(op[i], 0), a[i]));
            minMap.put(op[i], Math.min(minMap.getOrDefault(op[i], Integer.MAX_VALUE), a[i]));
        }
        
        int res = 0;
        for (int i = 0; i < op.length; i++) {
            res = Math.max(res, maxMap.get(op[i]) - minMap.get(op[i]));
        }
        
        return res;
    }
}

时空复杂度 O ( n ) O(n) O(n) n n n为数组长度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值