原始题目:
给定一个无序的整数序列, 找最长的连续数字序列。
例如:
给定[100, 4, 200, 1, 3, 2],
最长的连续数字序列是[1, 2, 3, 4]。
小菜给出的解法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
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<_array.length;i++){ if (_array[i] != _array[i+1]){ _arrayTemp.push(_array[i]); } } _array = _arrayTemp.slice(); _arrayTemp = []; //parse array parseLogic.addItem(); for (i = 0;i<_array.length;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。
返回值:
此方法不会改变传入的数组,会返回一个包含最大序列的新数组。
调用示例:
1
2
|
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] |