Skip to content

京东 校招 笔试 ​

2023-03-04 19:00

  • 简单题 小红舞会

  • 直接过 不会

  • 输入一个正整数 n,返回一个长度为 n、元素为[1, n]的数组的所有排列,然后对数组求权值,求输入 n 后得到的所有数组的权值之和

    • 例如输入 2,返回[2, 1]、[1, 2]、[1, 1]、[2, 2]
    • 权值为 一个数字的最大数的出现次数 例如 [1, 2, 2, 3] 最大值为3,出现1次 权值为1
ts
function getRandomArray(n) {
  if (n === 1) {
    return [[1]]
  }
  const result = []
  const prev = getRandomArray(n - 1)
  for (let i = 0; i < prev.length; i++) {
    for (let j = 0; j < n; j++) {
      const temp = prev[i].slice()
      temp.splice(j, 0, n)
      result.push(temp)
    }
  }
  // 元素全相同的情况
  for (let i = 0; i < n; i++) {
    const temp = []
    for (let j = 0; j < n; j++) {
      temp.push(n)
    }
    result.push(temp)
  }

  return result
}

function getWeight(arr) {
  let max = 0
  let weight = 0
  arr.forEach(item => {
    if (max < item) {
      max = item
    }
  })
  arr.forEach(item => {
    if (max === item) {
      weight = weight + 1
    }
  })
  return weight
}
let i = 0
getRandomArray(2).forEach(item => {
  console.log(item)
  i += getWeight(item)
})
console.log(i)

Released under the MIT License.