牛客网2016.4.11(两个数相加为sum/计数一个int型的二进制有多少个1/二叉树是否左右对称)
2024-08-30 12:35:49
求最小的两个数相加为sum
//求最小的两个数相加为sum
public ArrayList<Integer> FindNumbersWithSum(int [] array,int sum) {
List<Integer> list = new ArrayList<Integer>();
if(array == null || array.length==0){
return (ArrayList<Integer>) list;
}
for(int i=0;i<array.length-1;i++){
for(int j=i+1;j<array.length;j++){
if(array[i]+array[j] == sum){
list.add(array[i]);
list.add(array[j]);
break;
}
}
if(list.size()!=0){
break;
}
}
//没找到就返回空集合
return (ArrayList<Integer>) list;
}
计数一个int型的二进制有多少个1,难点在负数需要补码存
public int MoreThan0(int n) {
int cnt = 0;
char []c = Integer.toBinaryString(n).toCharArray();
for (char d : c) {
if(d=='1'){
cnt++;
}
}
return cnt;
}
求一个二叉树是否左右对称
- 中心处理方法
- 思路,利用栈队列的特性,进行层比较
import java.util.LinkedList;
import java.util.Stack;
public class Solution {
boolean isSymmetrical(TreeNode pRoot) {
Stack<TreeNode> stack = new Stack<TreeNode>();
Stack<TreeNode> StackSon = new Stack<TreeNode>();
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
stack.push(pRoot);
queue.offer(pRoot);
TreeNode bt1 = null;
TreeNode bt2 = null;
while(stack.size()!=0 || queue.size()!=0){
while(stack.size()!=0){
//出队和出栈
bt1 = stack.pop();
bt2 = queue.poll();
//比较镜像元素
if(bt1==null || bt2==null){
break;
}
if(bt1.val != bt2.val){
return false;
}
//入队
queue.offer(bt1.right);
queue.offer(bt1.left);
//栈的中转队列
StackSon.push(bt2.right);
StackSon.push(bt2.left);
}
while(StackSon.size()!=0){
stack.push(StackSon.pop());
}
}
return true;
}
public static void main(String[] args) {
int a[] = {8,6,6,5,7,7,5};
TreeNode root= new CreatTree().CreatTreeWay(a);
System.out.println(new Solution().isSymmetrical(root));
}
}
- 按层创建二叉树
import java.util.LinkedList;
public class CreatTree {
TreeNode root = null;
public TreeNode CreatTreeWay(int a[]){
if(a==null || a.length==0 ){
return null;
}
if(root == null){
root = new TreeNode(a[0]);
}else{
return root;
}
LinkedList<TreeNode> list = new LinkedList<TreeNode>();
list.offer(root);
TreeNode node = null;
for (int i = 1; i < a.length && list.size()!=0; i++) {
node = list.poll();
node.left = new TreeNode(a[i]);
list.offer(node.left);
if(i+1<a.length){
node.right = new TreeNode(a[i+1]);
list.offer(node.right);
}
}
return root;
}
public static void main(String[] args) {
int a[] = {8,6,6,5,7,7,5};
new CreatTree().CreatTreeWay(a);
}
}
- 忘了提供二叉树的结点类了
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
最新文章
- PHP实现全排列(递归算法)
- OSI7层模型详解
- LruCache为GridView异步加载大量网络图片
- 第二章 约束和排序数据(SQL基础)
- 关于openoffice英文乱码的问题
- 使用Linux的命令行工具做简单的文本分析
- [C#] 常用函数
- oracle存储过程的例子
- centos安装wget 及配置(转)
- HDU-1495 非常可乐 (嵌套结构体-广搜 对比 一般广搜)
- 初始Spring MVC——练手小项目
- vue实现简单日历
- ROS 双目标定
- Android ROM资源文件存放位置
- 消息队列第一篇:MessageQueue介绍
- “System.InvalidOperationException”类型的未经处理的异常在 ESRI.ArcGIS.AxControls.dll 中发生
- 解决 E: Could not get lock /var/lib/apt/lists/lock
- 关于RAM与ROM的区别与理解
- wpf- DataGrid 常用属性和事件
- SpringMVC传递数据的流线图