【7 kyu】Sum of two lowest positive integers

原题目

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<len; i++){
    var num = numbers[i];
    if(num < minNums[0]) {
      minNums = [num, minNums[0]];
    } else if(num < minNums[1]){
      minNums[1] = num;
    }
  }
  return minNums[0] + minNums[1];
};

Clever Solution

function sumTwoSmallestNumbers(numbers) {  
  var [ a, b ] = numbers.sort((a, b) => a - b)
  return a + b
}

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


对比

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值