深信服9.1前端编程题
第一题,给两个位置,反转中间的字符串
function solve(str,start,end){ let arr=str.split(''), startIndex=str.indexOf(start), endIndex=str.lastIndexOf(end); // console.log({startIndex,endIndex}); if(startIndex<0)startIndex=0; if(endIndex<0)endIndex=arr.length-1; while(startIndex<endIndex){ [arr[startIndex],arr[endIndex]]=[arr[endIndex],arr[startIndex]]; startIndex++,endIndex--; } return arr.join(''); }第二题,队列某个元素比较k次最大
function solve(arr,k){ let curK=0,curNum=arr.shift(); while(curK<k){ if(curNum<arr[0]){ curK=1; arr.push(curNum); curNum=arr.shift(); }else{ curK++; arr.push(arr.shift()); } } return curNum; }第三题,求哪个城市到其他城市的最短路径总和最小(弗洛伊德)
function solve(arr) { let len = arr.length, cnt = 0, map = new Map(); //方便处理 for (let i = 0; i < len; i++) { const [from, to] = arr[i]; if (!map.has(from)) { map.set(from, cnt++); map.set(cnt - 1, from); } if (!map.has(to)) { map.set(to, cnt++); map.set(cnt - 1, to); } } let dp = Array.from({ length: cnt }, () => Array.from({ length: cnt }, () => Infinity)); for (let i = 0; i < len; i++) { //这里是单向的 const [from, to, w] = arr[i]; dp[map.get(from)][map.get(to)] = w; dp[map.get(from)][map.get(from)]=0; dp[map.get(to)][map.get(to)]=0; } // console.log({ dp ,map,cnt}); //暴力会闭环,我们需要使用floyed算法 //floyed算法是指两地的最小距离需要在通过第三个地点进行更新 for (let k = 0; k < cnt; k++) { for (let i = 0; i < cnt; i++) { for (let j = 0; j < cnt; j++) { if (dp[i][j] > (dp[i][k] + dp[k][j])) { dp[i][j] = dp[i][k] + dp[k][j]; } } } } let solveArr=dp.map(arr=>arr.reduce((a,b)=>a+b),0), minValue=Math.min(...solveArr), minIndex=solveArr.indexOf(minValue), res=map.get(minIndex); // console.log({res}); return res; }