[2016/06/24] LeetCode / Java - Day 02 -
2016-06-24 16:20
573 查看
258. Add Digits
Given a non-negative integer num, repeatedly add all its digits until the result has only
one digit.
For example:
Given
num = 38, the process is like:
3 + 8 = 11,
1 + 1 = 2. Since
2has
only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
Hint:
A naive implementation of the above process is trivial. Could you come up with other methods?
What are all the possible results?
How do they occur, periodically or randomly?
You may find this Wikipedia article useful.
思路:一道涨姿势的题目。。直接运用https://en.wikipedia.org/wiki/Digital_root里的结论即可。
public class Solution {
public static int addDigits(int num) {
return (num-9*((num-1)/9));
}
}
104. Maximum Depth of Binary
Tree
Given a binary tree, find its maximum depth.The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
思路:嗯,总算是没有白看数据结构。。一开始拿到这道题我是懵逼的,但是仔细想了想。。试了试。。就出来了(惊呆。我得说AC的时候我是很意外的→
→思路很简单,就是递归,然后比较一下递归回来的左子树和右子树哪个深度大,就采用哪个。。然后不要忘了空树的深度是0.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public static int maxDepth(TreeNode root) {
if(root == null) return 0;
int maxl= 1;
int maxr=1;
if(root.left!=null)
{
maxl =1 + maxDepth(root.left);
}
if (root.right != null){
maxr = 1 + maxDepth(root.right);
}
return maxl>maxr?maxl:maxr;
}
}
136.
Single Number
Given an array of integers, every element appears twice except for one. Find that single one.Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
【思路】这个我是真的想不到。。。想到用XOR的人真是神人。。。
public class Solution { public static int singleNumber(int[] nums) { int m=0; for(int i=0; i<nums.length;i++){ m=m^nums[i]; } return m; } }
相关文章推荐
- JAVA读写文件,如何避免中文乱码
- Java获取音频文件(MP3)的播放时长
- java标识符类型的命名规则
- Synchronized(一)------java中Synchronized的用法
- java对象的访问
- java nio 常见的nio类, nio 写文件方法, nio 比io 的优势
- Java正则获取邮箱
- eclipse最有用快捷键整理
- Elasticsearch java API (5)Transport Client
- java编程心得(持续更新)
- java自学之旅(3)测试RandomAccessFile常用方法
- 华为机试---最大间隔
- java.util.concurrent
- Elasticsearch java API (4)部署在JBoss EAP6模块
- SpringMVC+Shiro权限管理
- Java NIO Channel
- Java正则抓取Email
- 玩转Eclipse开发工具(三)
- java创建二维码
- javaWeb程序的web.xml的作用