摘要:原題目題目有一個不少于四個元素的數(shù)組,計算其中兩個最小值的和。對比我寫的方法比較常規(guī),中采用了的解構(gòu)賦值和箭頭函數(shù)
原題目
Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 integers. No floats or empty arrays will be passed.
For example, when an array is passed like [19,5,42,2,77], the output should be 7.
[10,343445353,3453445,3453545353453] should return 3453455.
Hint: Do not modify the original array.
題目:有一個不少于四個元素的數(shù)組,計算其中兩個最小值的和。
思路:找出兩個最小的元素,然后求和
My Solutionfunction sumTwoSmallestNumbers(numbers) { var arr = numbers.sort(function(x, y) { return x - y; }); return arr[0] + arr[1]; };
雖然,上面的方法通過了系統(tǒng)的測試,但是原始數(shù)組卻被改變了!??!
MDN - Array.prototype.sort()
The sort() method sorts the elements of an array in place and returns the array.
function sumTwoSmallestNumbers(numbers) { var minNums = [numbers[0], numbers[1]].sort(function(x, y) {return x-y}); var len = numbers.length; for(i=2; iClever Solution function sumTwoSmallestNumbers(numbers) { var [ a, b ] = numbers.sort((a, b) => a - b) return a + b }? 被標(biāo)注“clever”對多的答案也用了sort, 也改變了原數(shù)組。
對比我寫的方法比較常規(guī),clever solution中采用了ES6的解構(gòu)賦值和箭頭函數(shù)
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://www.ezyhdfw.cn/yun/88777.html
摘要:月下半旬攻略道題,目前已攻略題。目前簡單難度攻略已經(jīng)到題,所以后面會調(diào)整自己,在刷算法與數(shù)據(jù)結(jié)構(gòu)的同時,攻略中等難度的題目。 Create by jsliang on 2019-07-30 16:15:37 Recently revised in 2019-07-30 17:04:20 7 月下半旬攻略 45 道題,目前已攻略 100 題。 一 目錄 不折騰的前端,和咸魚有什么區(qū)別...
摘要:在線網(wǎng)站地址我的微信公眾號完整題目列表從年月日起,每天更新一題,順序從易到難,目前已更新個題。這是項目地址歡迎一起交流學(xué)習(xí)。 這篇文章記錄我練習(xí)的 LeetCode 題目,語言 JavaScript。 在線網(wǎng)站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公眾號: showImg(htt...
摘要:原題目題目有一個隊列,排到的人,再次排到隊尾,并將自己變成雙倍。個人也覺得減法更一點(diǎn) 原題目 Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a Double Cola drink vending machine; there are no other people in the queue. The f...
摘要:前言從開始寫相關(guān)的博客到現(xiàn)在也蠻多篇了。而且當(dāng)時也沒有按順序?qū)懍F(xiàn)在翻起來覺得蠻亂的??赡艽蠹铱粗卜浅2环奖?。所以在這里做個索引嘻嘻。順序整理更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新 前言 從開始寫leetcode相關(guān)的博客到現(xiàn)在也蠻多篇了。而且當(dāng)時也沒有按順序?qū)憽F(xiàn)在翻起來覺得蠻亂的??赡艽蠹铱粗卜浅2环奖恪K栽谶@里做個索引嘻嘻。 順序整理 1~50 1...
閱讀 722·2021-10-09 09:41
閱讀 715·2019-08-30 15:53
閱讀 1143·2019-08-30 15:53
閱讀 1272·2019-08-30 11:01
閱讀 1637·2019-08-29 17:31
閱讀 1061·2019-08-29 14:05
閱讀 1785·2019-08-29 12:49
閱讀 469·2019-08-28 18:17