题目地址:
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为数组长度。