257. Binary Tree Paths
类似于分治法吧。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<String>();
if(root==null)
return res;
else{
if(root.left == null && root.right == null)
res.add(root.val+"");
if(root.left!=null){
List<String> left = binaryTreePaths(root.left);
for(int i=0;i<left.size();i++){
res.add(root.val +"->" + left.get(i));
}
}
if(root.right!=null){
List<String> right = binaryTreePaths(root.right);
for(int i=0;i<right.size();i++){
res.add(root.val +"->" + right.get(i));
}
}
}
return res;
}
}
258. Add Digits
小trick
class Solution {
public int addDigits(int num) {
int block = (num-1)/9;
return num - (9*block);
}
}
260. Single Number III
既然有两个数只出现了一次,那么这两个数至少有一位不一样,即异或不为0,那么可以根据这一位将数据分为两组,每一组再根据lian ge
class Solution {
public int[] singleNumber(int[] nums) {
int res = 0;
for(int num:nums){
res ^= num;
}
int seperator = 1;
while((seperator & res) == 0){
seperator <<= 1;
}
int[] result = new int[2];
for(int num:nums){
if((num & seperator) == 0)
result[0] ^= num;
else
result[1] ^= num;
}
return result;
}
}