You could sort the array and then run through it and then see if the next (or previous) index is the same as the current.(您可以对数组进行排序,然后遍历整个数组,然后查看下一个(或上一个)索引是否与当前索引相同。)
Assuming your sort algorithm is good, this should be less than O(n 2 ):(假设您的排序算法很好,则该值应小于O(n 2 ):)
var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7]; var sorted_arr = arr.slice().sort(); // You can define the comparing function here. // JS by default uses a crappy string compare. // (we use slice to clone the array so the // original array won't be modified) var results = []; for (var i = 0; i < sorted_arr.length - 1; i++) { if (sorted_arr[i + 1] == sorted_arr[i]) { results.push(sorted_arr[i]); } } console.log(results);
In case, if you are to return as a function for duplicates.(以防万一,如果要作为重复函数返回。) This is for similar type of case.(这是类似情况。)
Reference: https://stackoverflow.com/a/57532964/8119511(参考: https : //stackoverflow.com/a/57532964/8119511) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…