【算法题】内存冷热标记(js)

【算法题】内存冷热标记(js)_第1张图片
【算法题】内存冷热标记(js)_第2张图片
【算法题】内存冷热标记(js)_第3张图片
因此热内存为2

解法:

const lines = ["10", "1 2 1 2 1 2 1 2 1 2", "5"];
const lines2 = ["5", "1 2 3 4 5", "3"];
const lines3 = ["10", "2 1 2 1 2 1 2 1 2 1", "5"];
function solution(lines) {
  const num = parseInt(lines[0]);
  const arr = lines[1].split(" ").map((item) => parseInt(item));
  const max = parseInt(lines[2]);
  const record = {};
  for (let i = 0; i < arr.length; i++) {
    if (record[arr[i]]) {
      record[arr[i]] += 1;
    } else {
      record[arr[i]] = 1;
    }
  }
  const result = [];
  Object.keys(record).map((key) => {
    if (record[key] >= max) {
      result.push({
        key,
        value: record[key],
      });
    }
  });
  if (result.length < 1) {
    return 0;
  } else {
    const sortResult = result.sort((a, b) =>
      a.value !== b.value ? b.value - a.value : a.key.localeCompare(b.key)
    );
    return (
      sortResult.length + "\n" + sortResult.map((item) => item.key).join("\n")
    );
  }
}

console.log(solution(lines));
/* 
10
1 2 1 2 1 2 1 2 1 2
5 
=>
2
1
2

5
1 2 3 4 5
3
=>
0

 */

你可能感兴趣的:(算法题,javascript,算法,开发语言)