【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.javascript

For example, when an array is passed like [19,5,42,2,77], the output should be 7.java

[10,343445353,3453445,3453545353453] should return 3453455.數組

Hint: Do not modify the original array.函數

題目:有一個很多於四個元素的數組,計算其中兩個最小值的和。測試

思路:找出兩個最小的元素,而後求和prototype

My Solution

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

雖然,上面的方法經過了系統的測試,可是原始數組卻被改變了!!!code

MDN - Array.prototype.sort()
The sort() method sorts the elements of an array in place and returns the array.ip

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, 也改變了原數組。element


對比

我寫的方法比較常規,clever solution中採用了ES6的解構賦值和箭頭函數get

相關文章
相關標籤/搜索