publicclassSolution{int[] preorder;HashMap<Integer,Integer> dic =newHashMap<>();publicTreeNodebuildTree(int[] preorder,int[] inorder){this.preorder = preorder;for(int i =0; i < inorder.length; i++){dic.put(inorder[i], i);}returnrecur(0,0, inorder.length -1);}TreeNoderecur(int root,int left,int right){if(left > right){// 递归终止returnnull;}// 建立根节点TreeNode node =newTreeNode(preorder[root]);// 划分根节点、左子树、右子树int i = dic.get(preorder[root]);// 开启左子树递归node.left =recur(root +1, left, i -1);// 开启右子树递归 i - left + root + 1 含义为 根节点索引 + 左子树长度 + 1node.right =recur(root + i - left +1, i +1, right);// 回溯返回根节点return node;}publicclassTreeNode{int val;TreeNode left;TreeNode right;TreeNode(int x){val = x;}}}
二、数值的整数次方
publicclassSolution{publicdoublemyPow(double x,int n){long b = n;double res =1.0;if(b <0){x =1/ x;b =-b;}while(b >0){if((b &1)==1){res *= x;}x *= x;b >>=1;}return res;}}
三、打印从 1 到最大的 n 位数
publicclassSolution{publicint[]printNumbers(int n){int[] res =newint[(int)Math.pow(10, n)-1];for(int i =0; i < res.length; i++){res[i]= i +1;}return res;}}
四、二叉搜索树的后序遍历序列
publicclassSolution{publicbooleanverifyPostorder(int[] postorder){Stack<Integer> stack =newStack<>();int root =Integer.MAX_VALUE;for(int i = postorder.length -1; i >=0; i--){if(postorder[i]> root){returnfalse;}while(!stack.isEmpty()&& stack.peek()> postorder[i]){root = stack.pop();}stack.add(postorder[i]);}returntrue;}}
五、数组中的逆序对
publicclassSolution{int[] nums, tmp;publicintreversePairs(int[] nums){this.nums = nums;tmp =newint[nums.length];returnmergeSort(0, nums.length -1);}privateintmergeSort(int l,int r){// 终止条件if(l >= r){return0;}// 递归划分int m =(l + r)/2;int res =mergeSort(l, m)+mergeSort(m +1, r);// 合并阶段int i = l, j = m +1;for(int k = l; k <= r; k++){tmp[k]= nums[k];}for(int k = l; k <= r; k++){if(i == m +1){nums[k]= tmp[j++];}elseif(j == r +1|| tmp[i]<= tmp[j])nums[k]= tmp[i++];else{nums[k]= tmp[j++];res += m - i +1;// 统计逆序对}}return res;}}
for 循环允许您编写一个执行特定次数的循环的重复控制结构。
语法
C 中 for 循环的语法:
for ( init; condition; increment )
{statement(s);
}下面是 for 循环的控制流:
init 会首先被执行,且只会执行一次。这一步允许您声明并初始化任…