2012-05-24 85 views
2

給定一個未分類的正整數數組,編寫一個函數,用於查找3個連續數字(升序或降序)的運行並返回開始運行的索引。如果找不到這樣的運行,則返回null。在Javascript中過濾數組以找到3個連續數字

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

回答

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

現場演示:http://jsfiddle.net/Cc4DT/1/

相關問題