【算法题】免单统计(js)

2023-12-13 20:05:39

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

const line1 = [
  "3",
  "2019-01-01 00:00:00.001",
  "2019-01-01 00:00:00.002",
  "2019-01-01 00:00:00.003",
];
const line2 = [
  "3",
  "2019-01-01 08:59:00.123",
  "2019-01-01 08:59:00.123",
  "2018-12-28 10:08:00.999",
];
const line3 = [
  "5",
  "2019-01-01 00:00:00.004",
  "2019-01-01 00:00:00.004",
  "2019-01-01 00:00:01.006",
  "2019-01-01 00:00:01.006",
  "2019-01-01 00:00:01.005",
];

function solution(line) {
  const num = parseInt(line[0]);
  const times = [];
  for (let i = 1; i < 1 + num; i++) {
    times.push(line[i]);
  }
  const map = new Map();
  for (let i = 0; i < times.length; i++) {
    const timeParts = times[i].split(".")[0];
    const millisecondPart = parseInt(times[i].split(".")[1]);
    if (map.has(timeParts)) {
      if (millisecondPart < map.get(timeParts).value) {
        map.set(timeParts, {
          ...map.get(timeParts),
          value: millisecondPart,
          time: 1,
        });
      } else if (millisecondPart === map.get(timeParts).value) {
        map.set(timeParts, {
          ...map.get(timeParts),
          time: map.get(timeParts).time + 1,
        });
      } else {
        continue;
      }
    } else {
      map.set(timeParts, { value: millisecondPart, time: 1 });
    }
  }
  let sum = 0;
  for (const [key, value] of map) {
    sum += value.time;
  }
  return sum;
}

console.log(solution(line2));
/* 
3
2019-01-01 00:00:00.001
2019-01-01 00:00:00.002
2019-01-01 00:00:00.003
=>
1


3
2019-01-01 08:59:00.123
2019-01-01 08:59:00.123
2018-12-28 10:08:00.999
=>
3

5
2019-01-01 00:00:00.004
2019-01-01 00:00:00.004
2019-01-01 00:00:01.006
2019-01-01 00:00:01.006
2019-01-01 00:00:01.005
=>
3
 */

文章来源:https://blog.csdn.net/qq_43682422/article/details/134978323
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。