【发布时间】:2021-08-02 07:31:06
【问题描述】:
有点像duplicate,但不是同时,因为它在 python 中,所以我重新发布它。对于相同的输入,输出也不同。
我终于设法解决了一个复杂的任务,但我想出的算法很慢。
我很确定在最坏的情况下它在 n^2 + n 左右。
它应该遍历一个员工列表,并返回一个在共同项目上一起工作的天数最多的员工对列表。 (s很重要)
输入格式:
EmployeeID, ProjectID, StartDate, EndDate(NULL === today)
示例输入:
1,1,2019-7-4,2020-8-14
1,2,2019-12-25,2020-12-28
1,3,2018-10-12,NULL
1,4,2019-11-16,NULL
1,5,2020-1-5,2020-12-21
2,1,2018-10-3,NULL
2,2,2019-1-16,2020-3-24
2,3,2019-5-22,2019-12-26
2,4,2020-3-7,NULL
2,5,2018-1-24,2019-1-15
3,1,2019-3-21,2020-11-26
3,5,2019-9-28,2020-12-25
4,2,2018-10-22,NULL
4,3,2018-1-27,2020-8-28
5,3,2018-2-3,2020-10-14
5,5,2018-8-4,NULL
输出格式:
员工#1、员工#2、CommonProjectID、DaysWorked
示例输出:
1,2,1,407
1,2,2,90
1,2,3,219
1,2,4,513
这是我的看法,但正如我所说,它很慢,我被要求尝试优化它。现在已经为此工作了 5 个小时,但无法提出更好的建议。
export default function getHighestPair(empl) {
console.log(empl);
let pairs = {};
let daysTogether = {};
if (empl)
empl.forEach((el1) => {
/*
.slice() is used to exclude the current employee and employees before him
from the search which slightly reduces complexity. This is because
employee 5 + employee 13 is the same as employee 13 + employee 5
*/
empl.slice(empl.indexOf(el1) + 1, empl.length).forEach((el2) => {
// get start and end date of each of employee
if (el1[0] !== el2[0]) {
const startDate1 = new Date(el1[2]);
const endDate1 = el1[3] === "NULL" ? new Date() : new Date(el1[3]);
const startDate2 = new Date(el2[2]);
const endDate2 = el2[3] === "NULL" ? new Date() : new Date(el2[3]);
// check if they are in the same team (working on the same project)
if (el1[1] === el2[1]) {
if (startDate1 <= endDate2 && startDate2 <= endDate1) {
// calculate the start and end day that we need
const start = startDate1 <= startDate2 ? startDate2 : startDate1;
const end = endDate1 <= endDate2 ? endDate1 : endDate2;
if (end >= startDate2) {
// put them inside this formula and we get the time they have worked together in days
const diffTime = Math.abs(end - start);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
const x = `${el1[0]}${el2[0]}`;
if (!daysTogether[x]) Object.assign(daysTogether, { [x]: 0 });
daysTogether[x] = 1 * daysTogether[x] + diffDays;
if (!pairs[x]) Object.assign(pairs, { [x]: [] });
pairs[x] = [...pairs[x], [el1[0], el2[0], el1[1], diffDays]];
}
}
}
}
});
});
/*
gets the index of the pair that have worked together the longest toghether from
"daysTogether" which keeps count of the days for each project
*/
return pairs[
Object.keys(daysTogether).reduce((a, b) =>
daysTogether[a] > daysTogether[b] ? a : b
)
];
}
【问题讨论】:
-
如果之前计算一次工作时间或其他计算可能会快得多
-
@ClausBönnhoff 我怎样才能先计算工作时间?我真的不明白你想说什么。