资讯专栏INFORMATION COLUMN

【7 kyu】Sum of two lowest positive integers

fjcgreat / 1778人阅读

摘要:原题目题目有一个不少于四个元素的数组,计算其中两个最小值的和。对比我写的方法比较常规,中采用了的解构赋值和箭头函数

原题目

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.

题目:有一个不少于四个元素的数组,计算其中两个最小值的和。

思路:找出两个最小的元素,然后求和

My Solution
function sumTwoSmallestNumbers(numbers) {  
    var arr = numbers.sort(function(x, y) {
        return x - y;
    });
    return arr[0] + arr[1];
};

虽然,上面的方法通过了系统的测试,但是原始数组却被改变了!!!

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; i
Clever Solution
function sumTwoSmallestNumbers(numbers) {  
  var [ a, b ] = numbers.sort((a, b) => a - b)
  return a + b
}

? 被标注“clever”对多的答案也用了sort, 也改变了原数组。

对比

我写的方法比较常规,clever solution中采用了ES6的解构赋值和箭头函数

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/88777.html

相关文章

  • LeetCode 攻略 - 2019 年 7 月下半月汇总(100 题攻略)

    摘要:月下半旬攻略道题,目前已攻略题。目前简单难度攻略已经到题,所以后面会调整自己,在刷算法与数据结构的同时,攻略中等难度的题目。 Create by jsliang on 2019-07-30 16:15:37 Recently revised in 2019-07-30 17:04:20 7 月下半旬攻略 45 道题,目前已攻略 100 题。 一 目录 不折腾的前端,和咸鱼有什么区别...

    tain335 评论0 收藏0
  • 前端 | 每天一个 LeetCode

    摘要:在线网站地址我的微信公众号完整题目列表从年月日起,每天更新一题,顺序从易到难,目前已更新个题。这是项目地址欢迎一起交流学习。 这篇文章记录我练习的 LeetCode 题目,语言 JavaScript。 在线网站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公众号: showImg(htt...

    张汉庆 评论0 收藏0
  • 【5 kyu】Who Is Next?( Double Cola )

    摘要:原题目题目有一个队列,排到的人,再次排到队尾,并将自己变成双倍。个人也觉得减法更一点 原题目 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...

    pakolagij 评论0 收藏0
  • leetcode 部分解答索引(持续更新~)

    摘要:前言从开始写相关的博客到现在也蛮多篇了。而且当时也没有按顺序写现在翻起来觉得蛮乱的。可能大家看着也非常不方便。所以在这里做个索引嘻嘻。顺序整理更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新 前言 从开始写leetcode相关的博客到现在也蛮多篇了。而且当时也没有按顺序写~现在翻起来觉得蛮乱的。可能大家看着也非常不方便。所以在这里做个索引嘻嘻。 顺序整理 1~50 1...

    leo108 评论0 收藏0
  • 一些做着玩的题

    摘要:这是我在平时有时间的时候做的一些算法上的题目想看更新请移步这里题目描述解法这个问题当时拿到的时候是完全没有思路的,后面上网查询了一下这个题目,知道了使用斐波那契数列就能够解这道题目,,,当然百度作业帮上面也有相应的解法,套路就是题目为一 这是我在平时有时间的时候做的一些算法上的题目 想看更新请移步这里 题目: Climbing Stairs 描述 You are climbing a ...

    cheukyin 评论0 收藏0

发表评论

0条评论

fjcgreat

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<