给定一个未排序的正整数数组,编写一个函数,查找3个连续数字(升序或降序)的运行,并返回此类运行开始的索引。如果未找到此类运行,则返回null。
function findConsecutiveRuns(input:Array):Array
示例:[1,2,3,5,10,9,8,9,10,11,7]将返回[0,4,6,7]
我的JS技能有点生疏,这是我对此的尝试......
var numArray = [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7];
var newNumArray = [];
for(var i = 1; i < numArray.length; i++) {
if ((numArray[i] - numArray[i-1] != 1) || (numArray[i] + numArray[i+1] !=1) {
return 0;
}
else {
newNumArray.push(numArray[i]);
}
}
alert(newNumArray);
答案 0 :(得分:4)
下面:
function f ( arr ) {
var diff1, diff2, result = [];
for ( var i = 0, len = arr.length; i < len - 2; i += 1 ) {
diff1 = arr[i] - arr[i+1];
diff2 = arr[i+1] - arr[i+2];
if ( Math.abs( diff1 ) === 1 && diff1 === diff2 ) {
result.push( i );
}
}
return result.length > 0 ? result : null;
}