美文网首页让前端飞前端便利店
前端面试用来收尾的一道算法题

前端面试用来收尾的一道算法题

作者: 小遁哥 | 来源:发表于2023-04-18 15:49 被阅读0次

这道题衍生于足球应用,离职前被安排面试(求推荐),期间碰到个有趣的答案,特此记录下。

原题如下: 有 A、B、C 三个字符,要求输入出 A、B、C、AB、BC、AC、BC、ABC,顺序没要求

我的答案

因为我写足球应用的时候,只关注比赛场次之间的组合,最后是根据倍率排序的,就不在乎顺序

const charList = ["A", "B", "C"],
  resultList = [];

charList.forEach((char) => {
  let list = [];
  resultList.forEach((key) => list.push(key + char));
  resultList.push(char, ...list);
});

console.log(resultList);

结果是 ['A', 'B', 'AB', 'C', 'AC', 'BC', 'ABC'],以 ABC 为例,它是包含 AB、C

  • 当执行 A 到 resultList 没有,list 无新增,最后 resultList 有[ 'A' ]
  • 当执行 B 到 resultList 有[ 'A' ],list 新增[ 'AB' ] ,最后 resultList 有 [ 'A', 'B', 'AB' ]
  • 当执行 C 到 resultList 有[ 'A', 'B', 'AB' ],list 系新增[ 'AC', 'BC', 'ABC' ],最后 resultList 有['A', 'B', 'AB', 'C', 'AC', 'BC', 'ABC']

第二个答案

这个时候后面微信发给我的,执行发现不太对,输入越多,丢的值越多

var test = function(list='abcdfghijk') {
  const len = list.length
  const res = []
  for(let i = 0;i<len;i++) {
    const cur = list[i]
    res.push(cur)
    let left = i+1
    let right = len
    while(left<right) {
      const str = list.slice(left,right)
      res.push(
        cur + str
      )
      right--
    }
  }
  console.log(res,'resresres')
}

test()

但这个截取的想法我觉得很有趣,自己尝试了一下

const charList = ["A", "B", "C"],
  resultList = [];

charList.forEach((char, index) => {
  resultList.push(char);
  let leftIndex = index + 1,
    rightIndex = leftIndex + 1;
  while (leftIndex < charList.length) {
    resultList.push(char + charList.slice(leftIndex, rightIndex).join(""));
    rightIndex++;
    if (rightIndex > charList.length) {
      leftIndex++;
      rightIndex = leftIndex + 1;
    }
  }
});

console.log(resultList);

结果是['A','AB','ABC', 'AC','B','BC','C']

这个用双指针代替了'我的答案'中 list 的职责,当执行到 A 时候,左边指针从 1 开始,右边指针从 2 开始则取到 B,产出 AB,右边指针加 1 为 3 取道 BC,产出 ABC,右边指针的位置超过长度重置,这时候左边指针从 2 开始,右边指针从 3 开始,取到 C,产出 AC,开始处理 B。

相关文章

网友评论

    本文标题:前端面试用来收尾的一道算法题

    本文链接:https://www.haomeiwen.com/subject/byohjdtx.html