刚经过了华为的面试,虽然各种项目经理上被喷了不少,还好算法上稍微挽回一点
在leetcode上解题对于找工作无疑是帮助很大的
404. Sum of Left Leaves
Find the sum of all left leaves in a given binary tree.
Example:
3 / \ 9 20 / \ 15 7 There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
没啥好说的,树总离不开dfs,对树来说递归是非常不错的解题办法
public int sumOfLeftLeaves(TreeNode root) {
int leftValue=0;
int rightValue=0;
if(root==null){
return 0;
}else{
if(root.left!=null){
if(root.left.left==null&&root.left.right==null)
leftValue = root.left.val;
else
leftValue = sumOfLeftLeaves(root.left);
}
if(root.right!=null){
rightValue = sumOfLeftLeaves(root.right);
}
return leftValue+rightValue;
}
}
100. Same Tree
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
同样是树,同样的dfs,同样的递归
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null && q==null){
return true;
}else if(p==null || q==null){
return false;
}else{
if(p.val==q.val){
return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
}else{
return false;
}
}
}
405. Convert a Number to Hexadecimal
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
Note:
- All letters in hexadecimal (
a-f
) must be in lowercase. - The hexadecimal string must not contain extra leading
0
s. If the number is zero, it is represented by a single zero character'0'
; otherwise, the first character in the hexadecimal string will not be the zero character. - The given number is guaranteed to fit within the range of a 32-bit signed integer.
- You must not use any method provided by the library which converts/formats the number to hex directly.
Example 1:
Input: 26 Output: "1a"
Example 2:
Input: -1 Output: "ffffffff"
有收获的一道题
将一个数转换成二进制,按2取余是最常见的做法,在这道题中,对于正数来说是可以的,但是对于负数需要更多的处理
二进制和十六进制,都是和计算机关系紧密的数制,用正数除法和取余来做,都不如用位操作来做
位操作能直接对整型的二进制进行操作,其中无符号右移能非常简洁地配合负数的补码表示
public String toHex(int num) {
StringBuilder sb = new StringBuilder();
int cur=num;
int bit;
if(cur==0){
return 0+"";
}
while(cur!=0){
int oneHex = cur&15;
sb.append(hex(oneHex));
cur=cur>>>4;
}
return sb.reverse().toString();
}
public String hex(int num){
if(num<10)
return num+"";
else
return (char)(num-10+'a')+"";
}