亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我如何與數組中的其余元素進行比較

我如何與數組中的其余元素進行比較

白板的微信 2023-01-06 15:38:00
我正在研究一個 leetcode 問題,我想不出一種方法來將數組中的其余元素相互比較。我計算出最大和最小的數字,但與其他數字進行比較是我遇到的麻煩。您將在下面找到問題和我的工作:有多少數字小于當前數字?給定數組 nums,對于每個 nums[i],找出數組中有多少個數字小于它。也就是說,對于每個 nums[i],您必須計算有效 j 的數量,使得 j != i 和 nums[j] < nums[i]。返回數組中的答案。示例 1:Input: nums = [8,1,2,2,3]Output: [4,0,1,1,3]Explanation: For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). For nums[1]=1 does not exist any smaller number than it.For nums[2]=2 there exist one smaller number than it (1). For nums[3]=2 there exist one smaller number than it (1). For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).我的工作:var smallerNumbersThanCurrent = (nums) => {    const output = []    const max = nums.reduce(function(a, b) {        return Math.max(a, b);    });    const min = nums.reduce(function(a, b) {        return Math.min(a, b);    });    for(let i = 0; i < nums.length; i++){        if(nums[i] === max){            output.push(nums.length - 1)        } else if (nums[i] === min){            output.push(0)        }        else if (nums[i] < max && nums[i] > min){            //how do i compare with rest of the elements in the array?                }        }    }
查看完整描述

5 回答

?
一只甜甜圈

TA貢獻1836條經驗 獲得超5個贊

使用嵌套循環。


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}`);

沒有必要進行測試i != j,因為數字永遠不會低于自身。



查看完整回答
反對 回復 2023-01-06
?
米琪卡哇伊

TA貢獻1998條經驗 獲得超6個贊

一種更簡單的方法是簡單地對數組進行排序,然后元素的索引會告訴你有多少比它少:


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);

這樣做的另一個好處是您不必為每個數字搜索整個數組。



查看完整回答
反對 回復 2023-01-06
?
不負相思意

TA貢獻1777條經驗 獲得超10個贊

一種方法是在值小于當前值的條件下過濾數組,然后統計過濾后的數組中值的個數:


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 中進行計數,這應該會快得多:


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]


查看完整回答
反對 回復 2023-01-06
?
皈依舞

TA貢獻1851條經驗 獲得超3個贊

我喜歡:


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]));


查看完整回答
反對 回復 2023-01-06
?
紅顏莎娜

TA貢獻1842條經驗 獲得超13個贊

我對每個解決方案進行了性能測試。在我的電腦上(Intel Core I9-9900,64GB RAM)@StackSlave 的解決方案一直是最快的,其次是其他排序解決方案、reduce 解決方案、基本迭代和過濾器。您可以在下面自己運行測試:


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));

}



查看完整回答
反對 回復 2023-01-06
  • 5 回答
  • 0 關注
  • 222 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號