javascript - 替换 - Codewars 算法挑战

标签 javascript arrays algorithm sorting

This Codewars Challenge要求您

Choose exactly one element from the sequence and replace it with another integer > 0. You are not allowed to replace a number with itself, or to change no number at all.

我的思考过程是对输入数组从小到大进行排序,在前面添加1,然后从数组中删除最大的元素。这应该会产生尽可能最低的序列,因为我基本上是用 1 交换最大的元素。

示例:

([1,2,3,4,5]) => [1,1,2,3,4]

([4,2,1,3,5]) => [1,1,2,3,4]

([2,3,4,5,6]) => [1,2,3,4,5]

([2,2,2]) => [1,2,2]

([42]) => [1]

我尝试过:

function replacement(a){
  let sorted = a.sort((a, b) => a - b);
  sorted.unshift(1);
  return sorted.slice(0, sorted.length -1);
}

console.log(replacement([2,3,4,5,6]));

它适用于上面提到的测试,但似乎失败了 2/109。

wrong answer in test a=[1,1,1,1] - Expected: [1, 1, 2], instead got: [1, 1, 1]
wrong answer in test a=[1,1] - Expected: [2], instead got: [1]

我不明白为什么我的代码无法通过这些测试 - Codewars 没有显示失败测试的输入顺序。有任何想法吗?谢谢。

enter image description here

最佳答案

正如@vivek 指出的,我只是错过了检查最大值是否为1。如果是的话,我只需要将其替换为 2 即可。

function replacement(a){
  let sorted = a.sort((a, b) => a - b);
  if (sorted[sorted.length - 1] === 1){
    sorted.pop();
    sorted.push(2);
    return sorted;
  }
  sorted.unshift(1);
  return sorted.slice(0, sorted.length -1);
}

console.log(replacement([1, 1, 1, 1]));

关于javascript - 替换 - Codewars 算法挑战,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61162182/

相关文章:

java - 从 Java 8 中的单词字典中计算文本的值

确定语句/文本的正面或负面程度的算法

javascript - 使用 RegEx 匹配字符串列表

c++ - 选择排序方法似乎什么都不做

c++ - 在 C++ 中比较数组元素

javascript - 绑定(bind)到 Angular 中按钮的索引增量函数不会增加索引,也不会迭代数组

javascript - tinyMCE - 获取光标位置的内容

javascript - 在新选项卡中打开链接但没有 _blank 方法

javascript - 了解 Express Node.js 中的虚拟主机

python - 生成所有排列,其中排列长度 > Python 中元素的数量