代码之家  ›  专栏  ›  技术社区  ›  Justin Hawkins

在一个数组中返回两个数组,其中包含带特定字母的名称和不带指定字母的名称

  •  1
  • Justin Hawkins  · 技术社区  · 11 月前

    我正在进行for循环练习,并且只能使用for循环来迭代我正在处理的问题中的数组和字符串。 问题:返回值和2个数组的数组 //(1-名称中包含“a”的名称数组,2-名称中没有“a”名称的名称数组)

    我知道如何将包含字母“a”的名称推送到数组中,但不包含字母a的名称在迭代过程中被推送到数组的次数是多少,我怎么能让不包含字母“a”的名称数组只包含一次名称,而不是迭代的次数呢?我知道问题在于我嵌套了for循环,我想,但我就是看不见它,欢迎任何提示或建议!

    const arr1 = ['susan', 'meghan', 'timmy', 'tommy', 'thomas'];
    
    function itsSomething(array) {
      let bothArrays = [];
      let withA = [];
      let withoutA = [];
      for (let i = 0; i < array.length; i++) {
        let name = array[i];
        for (let x = 0; x < name.length; x++) {
          if (name[x] == 'a') {
            withA.push(name)
          } else {
            withoutA.push(name)
          }
        }
      }
      bothArrays.push(withA, withoutA);
      return bothArrays
    }
    
    console.log(itsSomething(arr1))
    2 回复  |  直到 11 月前
        1
  •  0
  •   Barmar    11 月前

    你的代码有两个问题:

    1. 一旦你发现 a 你应该打破常规。否则,如果单词有多个 你会推动它 withA 多次。
    2. 你正在努力 withoutA 每当你发现一个非- 性格,但仍有可能 在字符串的后面。你必须等到单词末尾才能知道它是否有 在其中。使用标志变量来保存此信息。

    const arr1 = ['susan', 'meghan', 'timmy', 'tommy', 'thomas'];
    
    function itsSomething(array) {
      let withA = [];
      let withoutA = [];
      for (let i = 0; i < array.length; i++) {
        let name = array[i];
        let foundA = false;
        for (let x = 0; x < name.length; x++) {
          if (name[x] == 'a') {
            withA.push(name);
            foundA = true;
            break;
          }
        }
        if (!foundA) {
          withoutA.push(name)
        }
      }
      return [withA, withoutA];
    }
    
    console.log(itsSomething(arr1))

    没有必要 bothArrays 变量。在返回这两个数组时,您可以简单地创建该数组。

        2
  •  0
  •   Derwyn Herrera    11 月前

    在这里,我为您带来了两种解决方案,第一种最简单的解决方案是使用includes方法,如下所示:

    function splitNames(array){
    let finalArray = [];
    let arraysWithA = [];
    let arraysWithoutA = [];
    for(let i = 0; i < array.length; i++){
      if(array[i].includes('a')){
        arraysWithA.push(array[i]);
      } else {
        arraysWithoutA.push(array[i]);
      }
    }
    finalArray.push(arraysWithA);
    finalArray.push(arraysWithoutA);
    return finalArray;
    

    }

    如果你正在练习循环,最好的方法就是Barmar提到的,使用flag变量来避免推送不必要的名称,就像这样

    function splitNamesWithLoop(array){
    let finalArray = [];
    let arraysWithA = [];
    let arraysWithoutA = [];
    
    for(let i = 0; i < array.length; i++){
      let strings = array[i];
      let flagForA = false;
      for( s of strings){
        if(s === "a"){
          arraysWithA.push(array[i]);
          flagForA = true;
          break;
        } 
      }
      if(flagForA === false){
        arraysWithoutA.push(strings);
      }
    }
    finalArray.push(arraysWithA);
    finalArray.push(arraysWithoutA);
    return finalArray;
    

    } 就性能而言,我强烈建议您使用它的第一个解决方案 时间复杂度为O(n),而第二个解对于所有嵌套循环的时间复杂度均为O(n*m)。希望这能有所帮助!