Last active
August 29, 2015 14:01
-
-
Save jikeytang/727aa186033107f609ad to your computer and use it in GitHub Desktop.
[ Javascript ] - 20140522-题目1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
输入n个整数,输出其中最小的k个。 | |
例如输入1,2,3,4,5,6,7和8这8个数字,则最小的4个数字为1,2,3和4。 | |
PS: | |
1. 回复时注意加上下面这句话,才会有语法高亮或格式缩进。 | |
```javascript | |
// you code | |
``` | |
2. 粘贴代码时请使用shift+tab,缩进前面的空白。 |
wzc602003869
commented
May 22, 2014
function getMin(arr, num) {
var len = arr.length, subArr = [];
subArr = arr.sort(function(a, b){ return a - b; }).slice(0, num);
return subArr;
}
getMin([1, 23, 41, 1, 2, 5, 65, 56], 5); // [1, 1, 2, 5, 23]
function getMin(arr, num) {
return arr.sort(function(a, b){ return a - b; }).slice(0, num);
}
getMin([1, 23, 41, 4, 2, 5, 65, 56, 28, 42], 6); // [1, 2, 4, 5, 23, 28]
function getMaxN(){
var args = arguments;
var arr = Array.prototype.slice.call(args);
var n = arr.pop();
return arr.sort(function(a, b){
return a - b;
}).slice(0, n);
}
console.log(getMaxN(4,5,7,9,2));
var arr = [52,412,51,5210,41,201,241,521,4];
function fn(arr, num){
var arr = arr.sort(function(a,b){return a-b});
if( num >= arr.length ){
return arr;
}else{
return arr.slice(0,num)
}
}
console.log( fn(arr, 4) )
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment