第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

重復的兩個總和問題 - 更慣用的 Javascript 解決方案

重復的兩個總和問題 - 更慣用的 Javascript 解決方案

有只小跳蛙 2021-11-18 16:17:19
給定一個包含重復的整數(shù)數(shù)組,返回一個數(shù)組,其中所有索引對的總和為零。[1, 2, 3, -1, 5, -5, 7, 9, -7, 2, -2] -> [ [ 3, 0 ], [ 5, 4 ], [ 8, 6 ], [ 10, 1 ], [ 10, 9 ] ]我的JS解決方案:function pairs(values, i) {  if (values) {    values.push(i);    return values;  }  return [i];}function twoSum(arr) {  const results = [];  const map = new Map();  arr.forEach((ele, i) => {    if (map.get(-ele)) {      map.get(-ele).forEach((e) => results.push([i, e]));    }    map.set(ele, pairs(map.get(ele), i));  });  return results;}來自 Ruby,這是我的 Ruby 解決方案:def two_sum(arr)  hash = Hash.new { |h, k| h[k] = [] }  arr.each.with_index.each_with_object([]) do |(ele, i), results|    if hash.key?(-ele)      hash[-ele].each { |e| results << [i, e] }    end    hash[ele] << i  endend這個想法是每個 hashmap 鍵都有一個數(shù)組,對于數(shù)組中的每個元素,我們檢查 hashmap 是否有 -element 鍵,如果有,則將當前索引和每個值的對推送到結果數(shù)組中。我怎樣才能使 JS 解決方案更慣用?我在 JS 默認庫中找不到以下內容(與 Ruby 相比):將一個可枚舉對象縮減為另一個可枚舉對象(each_with_object)。初始化一個映射,使每個新鍵對應一個對象(Hash.new([])、Hash.new(0) 等)。對選擇的解決方案進行了一點重構,最終得到了這樣的結果:function twoSum(arr) {  const hash = new Map();  return arr.reduce((results, ele, i) => {    if (hash.has(-ele)) hash.get(-ele).forEach((e) => results.push([i, e]));    hash.get(ele) ? hash.get(ele).push(i) : hash.set(ele, [i]);    return results;  }, []);}
查看完整描述

2 回答

?
喵喵時光機

TA貢獻1846條經(jīng)驗 獲得超7個贊

function two_sum(arr) {

    let hash = new Map();


    return arr.reduce((results, ele, i) => {

        if (hash.has(-ele)) {

            results = results.concat(hash.get(-ele).map(e => [i, e]))

        }


        hash.set(ele, hash.get(ele) || []);

        hash.get(ele).push(i);


        return results;


    }, []);

}


查看完整回答
反對 回復 2021-11-18
?
慕娘9325324

TA貢獻1783條經(jīng)驗 獲得超4個贊

像這樣的事情,也許:


const sumZeroIndexPairs = arr => {

  const hashMap = arr.reduce(

    (result, value, index, list) => {

      list.forEach((n, i) => {

        const key = [ index, i ].sort().join('_')

        const sum = value + n

        result[key] = sum

      })

      return result

    },

    {}

  );

  

  return Object.entries(hashMap)

    .filter( ([key, value]) => value === 0 )

    .map(([key]) => key.split('_'));

}


console.log(sumZeroIndexPairs([1, 2, 3, -1, 5, -5, 7, 9, -7, 2, -2]))


查看完整回答
反對 回復 2021-11-18
  • 2 回答
  • 0 關注
  • 156 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號