一个非空的整数列表

时间:2016-11-10 22:18:25

标签: javascript function

您将获得一个非空的整数列表。对于此任务,您应该返回一个列表,该列表仅包含此列表中的非唯一元素。为此,您需要删除所有唯一元素(仅包含在给定列表中的元素一次)。解决此任务时,请勿更改列表的顺序。示例:[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;
  }
}

2 个答案:

答案 0 :(得分:1)

我的解决方案:

  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;
            }
    
  3. 希望有所帮助

答案 1 :(得分:0)

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

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

相关问题