The JavaScript implementation lists the longest consecutive numbers in an array _javascript tips

Source: Internet
Author: User

Original topic:

Given a sequence of unordered integers, find the longest sequence of consecutive digits.

For example:

Given [100, 4, 200, 1, 3, 2],

The longest sequential number sequence is [1, 2, 3, 4].

The solution to the side dishes:

Copy Code code as follows:

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 ();
}


Call Description:

Method Name:

Maxsequence (Array,step)

Parameter description:

Array: the arrays to find. Necessary.

Step: Sequence Size (increment). Optionally, the default is 1.

return value:

This method does not change the passed-in array, and returns a new array that contains the largest sequence.

Call Example:

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]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.