求最小的两个数相加为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;
}
}