我正在准备面试,正在做一些练习题。问题是:
在一个数组中找到重复次数最多的整数。
这是我创建的函数和他们创建的函数。它们被适当地命名了。
var arr = [3, 6, 6, 1, 5, 8, 9, 6, 6]
function mine(arr) {
arr.sort()
var count = 0;
var integer = 0;
var tempCount = 1;
var tempInteger = 0;
var prevInt = null
for (var i = 0; i < arr.length; i++) {
tempInteger = arr[i]
if (i > 0) {
prevInt = arr[i - 1]
}
if (prevInt == arr[i]) {
tempCount += 1
if (tempCount > count) {
count = tempCount
integer = tempInteger
}
} else {
tempCount = 1
}
}
console.log("most repeated is: " + integer)
}
function theirs(a) {
var count = 1,
tempCount;
var popular = a[0];
var temp = 0;
for (var i = 0; i < (a.length - 1); i++) {
temp = a[i];
tempCount = 0;
for (var j = 1; j < a.length; j++) {
if (temp == a[j])
tempCount++;
}
if (tempCount > count) {
popular = temp;
count = tempCount;
}
}
console.log("most repeated is: " + popular)
}
console.time("mine")
mine(arr)
console.timeEnd("mine")
console.time("theirs")
theirs(arr)
console.timeEnd("theirs")
most repeated is: 6
mine: 16.929ms
most repeated is: 6
theirs: 0.760ms
我的函数为什么比他们的慢?
mine
函数中使用了sort
,而their
已经是排序好的数组。 - Grundyconsole.log("most repeated is: " + integer)
和console.log("most repeated is: " + popular)
这两行代码,然后得到了mine: 0.000ms, theirs 0.000ms
的结果。:-D - Grundy