脚本宝典收集整理的这篇文章主要介绍了【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.
思路:找出两个最小的元素,然后求和
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
, 也改变了原数组。
对比
以上是脚本宝典为你收集整理的【7 kyu】Sum of two lowest positive integers全部内容,希望文章能够帮你解决【7 kyu】Sum of two lowest positive integers所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。