javascript - a non-empty list of integers -
this question has answer here:
- remove duplicates javascript array 53 answers
- easiest way find duplicate values in javascript array 53 answers
you given non-empty list of integers. task, should return list consisting of non-unique elements in list. need remove unique elements (elements contained in given list once). when solving task, not change order of list. example: [1, 2, 3, 1, 3] 1 , 3 non-unique elements , result [1, 3, 1, 3].
function nonuniqueelements(data) { var array = []; (var = 0; < data.length; i++) { while (i >= 2) { array.push(i); } return data; } }
my solution:
- first loop on array count how each number appears in array
using map. total time o(n) and loop again on array , push new array number, if current number appears more 1 in map. total time o(n).
function nonuniqueelements(data) { //first loop on array , find duplications //create map numbers //the key number, //and value how each number appears in array var map = {}; (var i=0; < data.length; i++){ if (map[data[i]] == undefined){ //the number not exist in map, push map map[data[i]] = 0; } else {//the number alredy exists //increase counter map[data[i]] = map[data[i]] +1; } } //now, loop on array once again var nonuniquearray = []; (var i=0; < data.length; i++){ //if value of current element more 1 if (map[data[i]] > 0){ //push new nonuniquearray nonuniquearray.push(data[i]); } } //return non unique array return nonuniquearray; }
hope helps
Comments
Post a Comment