当前位置: 首页 > Web前端 > HTML5

算法小日常-01

时间:2023-04-05 21:42:24 HTML5

【104】二叉树的最大深度有两种解法。递归比较容易想到,迭代需要重新思考?1.递归函数maxDepth(root){if(!root){return0;}else{letleft=maxDepth(root.left);让right=maxDepth(root.right);返回Math.max(左,右)+1;}}2.迭代,使用层序遍历累加constmaxDepth=root=>{if(!root)return0letqueue=[root],n=0console.log('queue',queue.length)while(queue.length){letarr=[]while(queue.length){letcurr=queue.shift()console.log('curr',curr)console.log('arr',arr)if(curr.left)arr.push(curr.left)如果(curr.right)arr.push(curr.right)}n++queue=arr}returnn}[122]买卖股票的最佳时机2两种解决方法:第一种是自己搞的笨方法,第二种是参考别人的思路1、/***@param{number[]}prices*@return{number}*/varmaxProfit=function(prices){if(prices.length<2)return0;让结果=0;让small=prices[0]for(vari=0;iprices[i+1]){result+=prices[i]-small;小=价格[i+1];}else{result+=prices[i]-小;小=价格[i];}}}返回结果;};2.贪心算法,每天一步,只取正收益,不需要负收益(设置为0)每天的收益=今天的股价-昨天的股价。varmaxProfit=function(prices){letsum=0for(leti=1;i