【问题标题】:a non-empty list of integers [duplicate]一个非空的整数列表[重复]
【发布时间】:2017-03-25 02:17:54
【问题描述】:

给你一个非空的整数列表。对于此任务,您应该返回一个仅包含此列表中的非唯一元素的列表。为此,您需要删除所有唯一元素(给定列表中仅包含一次的元素)。解决此任务时,不要更改列表的顺序。示例:[1, 2, 3, 1, 3] 1 和 3 个非唯一元素,结果将是 [1, 3, 1, 3]

function nonUniqueElements(data) {
  var array = [];
  for (var i = 0; i < data.length; i++) {
      while (i >= 2) {
         array.push(i);
      }
      return data;
  }
}

【问题讨论】:

  • 你所做的只是检查i是否大于t2o,它不会检查数字是否存在。
  • 您能在不提供解决方案的情况下给我任何提示吗?
  • 遍历数组并查看元素是否存在多次。
  • 我以为我已经在遍历一个数组了
  • 嗯,似乎我读错了 this 问题 - 出于某种原因,我认为它是“删除重复项,包括他们拥有的所有重复项”,但实际上恰恰相反- “只留下 重复项”。在这种情况下,删除重复问题确实有效,只需执行 相反

标签: javascript function


【解决方案1】:

使用遍历同一数组的嵌套 for 循环,在本例中为数据。

首先检查每个循环的索引是否相同。如果是什么都不做。如果它们不相同,请检查值。如果值相等,则推送到数组。

【讨论】:

    【解决方案2】:

    我的解决方案:

    1. 首先循环数组以计算每个数字在数组中出现的次数
      通过使用地图。总时间为 O(n)
    2. 然后再次循环遍历数组并推送到新数组 数字,仅当当前数字在地图中出现大于 1 时。 总时间为 O(n)。

       function nonUniqueElements(data) {
      
                //first loop over the array and find all duplications
                //create a map with all the numbers
                //the key will be the number, 
                //and the value will be how much each number appears in the array
                var map = {};
                for (var i=0; i < data.length; i++){
                  if (map[data[i]] == undefined){
                    //the number does not exist in the map, than push to map
                     map[data[i]] = 0;
      
                  } else {//the number alredy exists
                    //increase the counter
                     map[data[i]] = map[data[i]] +1;
                  }
                }
      
      
                //now, loop over the array once again
                var nonUniqueArray = [];
                  for (var i=0; i < data.length; i++){
                    //if the value of the current element is more than 1
                    if (map[data[i]] > 0){
                      //push to the new nonUniqueArray
                      nonUniqueArray.push(data[i]);
                    }
                  }
      
                //return the  non unique array
                return nonUniqueArray;
              }
      

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-05
      • 1970-01-01
      • 2015-05-12
      • 1970-01-01
      • 1970-01-01
      • 2015-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多