剑指offer_2.1_Day_5
2024-08-31 19:28:37
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) { ArrayList<Integer> num = new ArrayList<Integer>();
while(listNode!=null)
{
num.add(0,listNode.val);
listNode=listNode.next;
}
return num;
}
}
新建一个动态链表 ArrayList<Integer> ArrayList = new ArrayList<Integer>();
add添加是在最末尾,因为是从尾到头打印,添加一个0改为添加到首位。
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
TreeNode root=reConstructBTree(pre,0,pre.length-1,in,0,in.length-1);
return root;
}
private TreeNode reConstructBTree(int [] pre,int startPre,int endPre,int [] in,int startIn,int endIn) { if(startPre>endPre||startIn>endIn)
return null;
TreeNode root=new TreeNode(pre[startPre]);
for(int i=startIn;i<=endIn;i++)
if(in[i]==pre[startPre]){
root.left=reConstructBTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1);
root.right=reConstructBTree(pre,i-startIn+startPre+1,endPre,in,i+1,endIn);
} return root;
}
}
原理还是很简单的,因为是前序和中序,那么前序第一个是根节点,中序对应的位置前为左叉树,后为右叉树,以此进行递归。
求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
public class Solution {
public int Sum_Solution(int n) {
int sum =(int)(Math.pow(n,2)+n);
return sum>>1; }
}
打个比方,1+到100是5050,×2就是10100,也就是100的平方加上100.也就是从1到100,可以看成,1到99再加上100,之后除以二。
public class Solution {
public int Sum_Solution(int n) {
int res = n;
boolean flag = (n>0)&&((res+=Sum_Solution(n-1))>0);
return res;
}
}
短路效果来实现递归。最后无法达成继续加法。
最新文章
- How to build a NFS Service
- SDL播放视频
- HYSBZ 2440 完全平方数(莫比乌斯反演)
- Divide Two Integers leetcode
- 性能测试一般过程与LR性能测试过程
- 6个常见的 PHP 安全性攻击
- pcDuino无显示器刷机与使用
- Azure上Linux VM DDOS攻击预防: 慢速攻击
- JAVA流读取文件并保存数据
- 查看java内存情况命令
- Spring详细教程
- Codeigniter使用HMVC(一)
- Windows远程桌面,连接被拒绝,因为没有授权此用户帐户进行远程登录。
- Java中内存溢出与内存泄露
- 大数据自学5-Python操作Hbase
- int __get_order(unsigned long size)
- Exception in thread ";main"; java.net.SocketTimeoutException: connect timed ou错误处理
- c++ 的类 和 类继承, 什么是c++中的基类和派生类?
- T4扩展程序
- 建立ARM交叉编译环境 (arm-none-linux-gnueabi-gcc with EABI)【转】