[2016/06/24] LeetCode / Java - Day 02 -
来源:互联网 发布:多益网络 编辑:程序博客网 时间:2024/05/30 05:13
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 2
has 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?
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; }}
- [2016/06/24] LeetCode / Java - Day 02 -
- [2016/06/28] LeetCode / Java - Day 06 -
- [2016/06/25] LeetCode / Java - Day 3 -
- [2016/06/26] LeetCode / Java - Day 04 -
- [2016/06/27] LeetCode / Java - Day 05 -
- [2016/06/29] LeetCode / Java - Day 07 -
- [2016/06/30] LeetCode / Java - Day 08 -
- [2016/07/06] LeetCode / Java - Day 13 -
- [2016/07/02] LeetCode / Java - Day 10 -
- [2016/07/01] LeetCode / Java - Day 09 -
- [2016/07/03] LeetCode / Java - Day 11 -
- [2016/07/05] LeetCode / Java - Day 12 -
- JAVA DAY DAY UP
- java自学日记 day 06
- JAVA SE — Day 06
- JAVA SE — Day 02
- Java study 06day-静态代码块
- java study 02day-关键字与标识符
- ORACLE常用系统表大全
- 第15周项目二—洗牌(1)
- ubunta 中mysql基本操作
- 外网调试局域网程序
- 嵌入式学习-uboot-lesson4.3-关闭看门狗和中断
- [2016/06/24] LeetCode / Java - Day 02 -
- ffmpeg初始化文件头信息时
- MyEclipse中配置JDK
- Shiro 3 shiroFilter
- Activity与布局初始化流程;
- C语言基础 bool形变量的头文件与输出
- java对象的访问
- 文件和文件系统
- java 如何判断操作系统是Linux还是Windows