一、在有序的数组中找到一个指定值的索引(二分查找)
var arr = [1,2,3,5,7,8,9,11,56,78,99]; function binarySearch(arr, val){ var low = 0, high = arr.length - 1; while(low <= high){ var mid = parseInt((low + high) / 2); if(val == arr[mid]){ return mid; }else if(val > arr[mid]){ low = mid + 1; }else if(val < arr[mid]){ high = mid - 1; }else{ return -1; } } return -1; } console.log(binarySearch(arr, 11));
二、判断数组是否为对称数组
function testSymmetry(arr){ //严谨性判断 if(arr.length == 0 || !(arr instanceof Array)){return false;} var low = 0, high = arr.length - 1; while(1){ if(low >= high){break;} if(arr[low] != arr[high]){return false;} low++; high--; } return true; }
三、查询子串首次出现的位置
var arr = ["l", "k", "j", "h", "g", "f", "d", "s", "a", "s", "d", "f", "g", "h", "k", "j", "h", "s"]; var subArr = ['s','d','f']; function findSubArrIndex(origin, sub){ //严谨判断 if(origin.length == 0 || sub.length == 0 || !(origin instanceof Array) || !(sub instanceof Array)){ return -1; } for(var index = 0; index <= origin.length - sub.length; index++){ //index控制子数组和原数组的哪一位开始比较 for(var j = 0; j < sub.length; j++){ if(sub[j] != origin[index + j]){break;} if(j == sub.length - 1){return index;} } } return -1; }
四、计算数组中最大的连续增长的子序列的长度,如[1,2,3,1,2,3,4,1,2,3,4,5,6,1]
function getMaxSequence(arr){ if( !arr || !(arr instanceof Array) ){return 0;} var nowMax = 1, max = 0; for(var i = 1; i < arr.length; i++){ if(arr[i] - arr[i-1] > 0){ nowMax++; }else{ max = nowMax > max ? nowMax : max; nowMax = 1; } } max = nowMax > max ? nowMax : max; return max; }
以上内容属二哥原创,整理自 "渡一教育Javascript课程" ,一个值得推荐的"渡一教育"。