原始题目:
给定一个无序的整数序列, 找最长的连续数字序列。
例如:
给定[100, 4, 200, 1, 3, 2],
最长的连续数字序列是[1, 2, 3, 4]。
小菜给出的解法:
复制代码 代码如下:
function maxsequence(array,step){
var _array = array.slice(), //clone array
_step = 1,
_arraytemp = [],
i = 0;
var parselogic = {
//result container
parseresults: [],
//set value to array,what's the last array of parseresults
set: function(n){
this.parseresults[this.parseresults.length-1].push(n);
},
//get the last array from parseresults
get: function(){
return this.parseresults[this.parseresults.length-1];
},
//put a new array in parseresults
additem: function(){
this.parseresults.push([]);
},
//sort parseresults
sortbyasc: function(){
this.parseresults.sort(function(a,b){
return a.length - b.length;
});
}
};
//check params
_step = step || _step;
//sort array by asc
_array.sort(function(a,b){
return a - b;
});
//remove repeat of data
for(i = 0;i if(_array[i] != _array[i+1]){
_arraytemp.push(_array[i]);
}
}
_array = _arraytemp.slice();
_arraytemp = [];
//parse array
parselogic.additem();
for(i = 0;i if(_array[i]+_step == _array[i+1]){
parselogic.set(_array[i]);
continue;
}
if(_array[i]-_step == _array[i-1]){
parselogic.set(_array[i]);
parselogic.additem();
}
}
//sort result
parselogic.sortbyasc();
//get the max sequence
return parselogic.get();
}
调用说明: 方法名称:
maxsequence(array,step)
参数说明:
array:要查找的数组。必要。
step:序列步长(增量)。可选,默认为1。
返回值:
此方法不会改变传入的数组,会返回一个包含最大序列的新数组。
调用示例:
maxsequence([5,7,2,4,0,3,9],1); //return [2,3,4,5]
maxsequence([5,7,2,4,0,3,9],2); //return [5,7,9]