5 回答

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超5個(gè)贊
使用嵌套循環(huán)。
nums = [8,1,2,2,3];
answer = [];
for (let i = 0; i < nums.length; i++) {
let count = 0;
for (let j = 0; j < nums.length; j++) {
if (nums[j] < nums[i]) {
count++;
}
}
answer.push(count);
console.log(`For nums[${i}]=${nums[i]} there are ${count} lower numbers`);
}
console.log(`Answer: ${answer}`);
沒(méi)有必要進(jìn)行測(cè)試i != j
,因?yàn)閿?shù)字永遠(yuǎn)不會(huì)低于自身。

TA貢獻(xiàn)1998條經(jīng)驗(yàn) 獲得超6個(gè)贊
一種更簡(jiǎn)單的方法是簡(jiǎn)單地對(duì)數(shù)組進(jìn)行排序,然后元素的索引會(huì)告訴你有多少比它少:
const nums = [8,1,2,2,3]
const sorted = [...nums].sort();
const result = nums.map((i) => {
return sorted.findIndex(s => s === i);
});
console.log(result);
這樣做的另一個(gè)好處是您不必為每個(gè)數(shù)字搜索整個(gè)數(shù)組。

TA貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超10個(gè)贊
一種方法是在值小于當(dāng)前值的條件下過(guò)濾數(shù)組,然后統(tǒng)計(jì)過(guò)濾后的數(shù)組中值的個(gè)數(shù):
const nums = [8,1,2,2,3];
const smallerNums = nums.map(v => nums.filter(n => n < v).length);
console.log(smallerNums); // [4,0,1,1,3]
或者,您可以在 reduce 中進(jìn)行計(jì)數(shù),這應(yīng)該會(huì)快得多:
const nums = [8, 1, 2, 2, 3];
const smallerNums = nums.map(v => nums.reduce((c, n) => c += (n < v), 0));
console.log(smallerNums); // [4,0,1,1,3]

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超3個(gè)贊
我喜歡:
function rankZero(array){
const s = [...array], r = [];
s.sort((a, b)=>{
return a - b;
});
for(let n of array){
r.push(s.indexOf(n));
}
return r;
}
console.log(rankZero([8, 1, 2, 2, 3]));

TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超13個(gè)贊
我對(duì)每個(gè)解決方案進(jìn)行了性能測(cè)試。在我的電腦上(Intel Core I9-9900,64GB RAM)@StackSlave 的解決方案一直是最快的,其次是其他排序解決方案、reduce 解決方案、基本迭代和過(guò)濾器。您可以在下面自己運(yùn)行測(cè)試:
const datalength = 1000;
const iterations = 100;
const getRandom = (min, max) => Math.random() * (max - min) + min;
const data = Array.from({
length: datalength
}, () => getRandom(1, 100));
const mapper = arr => arr.map(i => arr.filter(n => n < i).length);
const sorter = nums => {
const sorted = [...nums].sort();
const result = nums.map((i) => {
return sorted.findIndex(s => s === i);
});
};
const iterator = arr => {
const answer = [];
for (let i = 0; i < arr.length; i++) {
let count = 0;
for (let j = 0; j < arr.length; j++) {
if (arr[j] < arr[i]) {
count++;
}
}
answer.push(count);
}
return answer;
};
const rankZero = array => {
const s = [...array],
r = [];
s.sort((a, b) => {
return a - b;
});
for (let n of array) {
r.push(s.indexOf(n));
}
return r;
}
const reducer = arr => arr.map(v => arr.reduce((c, n) => c += (n < v), 0));
let fns = {
'iterator': iterator,
'mapper': mapper,
'sorter': sorter,
'reducer': reducer,
'rankZero': rankZero
}
for (let [name, fn] of Object.entries(fns)) {
let total = 0;
for (i = 0; i < iterations; i++) {
let t0 = performance.now();
fn(data);
let t1 = performance.now();
total += t1 - t0;
}
console.log(name, (total / iterations).toFixed(2));
}
添加回答
舉報(bào)