给定一个非空的整数列表。对于此任务,您应该返回一个仅包含此列表中非唯一元素的列表。为此,您需要删除所有唯一元素(在给定列表中只包含一次的元素)。在解决此任务时,不要更改列表的顺序。示例:[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;
}
}
我的解决方案:
- 第一个循环遍历数组,计算每个数字在数组中出现的次数
通过使用地图。总时间O(n) -
然后再次循环遍历数组并将数组推入新数组数字,仅当当前数字在地图中出现大于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; }
希望有所帮助
使用嵌套的for循环遍历同一个数组,在本例中为data.
首先检查每个循环的索引是否相同。如果是,什么也不做。如果它们不相同,请检查值。