面试笔试杂项积累-leetcode 246-260
来源:互联网 发布:centos 6.5 硬盘分区 编辑:程序博客网 时间:2024/06/18 14:01
257.257-Binary Tree Paths-Difficulty: Easy
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1 / \2 3 \ 5
All root-to-leaf paths are:
["1->2->5", "1->3"]
思路
存储所有根到叶的路径,
深度优先遍历
左右子节点都为null时是一个路径到头了
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */public class Solution { IList<string> fin = new List<string>(); public IList<string> BinaryTreePaths(TreeNode root) { getDeep(root, ""); return fin; } public void getDeep(TreeNode temp, string str) { if (temp != null) { if (temp.left == null && temp.right == null) fin.Add(str + temp.val); else { str += temp.val + "->"; if(temp.left!=null) getDeep(temp.left, str); if (temp.right != null) getDeep(temp.right, str); } } }}
258.258-Add Digits-Difficulty: Easy
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 thisWikipedia article useful.
方法一
思路
数字的每一位加在一起,直到加到个位数,返回个位数
转成string每一位加,直到位数为1
public class Solution { public int AddDigits(int num) { string str = num.ToString(); if (str.Length <= 1) return num; int temp = 0; while (str.Length > 1) { temp = 0; for (int i = 0; i < str.Length; i++) temp += str[i] - '0'; str = temp.ToString(); } return temp; }}
方法二
思路
参考:https://leetcode.com/discuss/80037/java-one-line-simple-answer
According to WIKI, we could compute the congruent root easily.
For number that from 0 to 9, the answer is themselves
For number that is divisible by 9, the answer is 9
Otherwise, the answer is the reminder after divided by 9
public int addDigits(int num) { return num>9?(num%9==0?9:num%9):num;}
- 面试笔试杂项积累-leetcode 246-260
- 面试笔试杂项积累-leetcode 1-5
- 面试笔试杂项积累-leetcode 6-10
- 面试笔试杂项积累-leetcode 11-15
- 面试笔试杂项积累-leetcode 16-20
- 面试笔试杂项积累-leetcode 21-25
- 面试笔试杂项积累-leetcode 26-30
- 面试笔试杂项积累-leetcode 31-35
- 面试笔试杂项积累-leetcode 36-40
- 面试笔试杂项积累-leetcode 41-45
- 面试笔试杂项积累-leetcode 46-50
- 面试笔试杂项积累-leetcode 51-55
- 面试笔试杂项积累-leetcode 56-60
- 面试笔试杂项积累-leetcode 61-65
- 面试笔试杂项积累-leetcode 66-70
- 面试笔试杂项积累-leetcode 71-75
- 面试笔试杂项积累-leetcode 76-80
- 面试笔试杂项积累-leetcode 81-85
- overlay机制
- Codeforces 479E Riding in a Lift (DP)
- 深入理解Java
- 欢迎使用CSDN-markdown编辑器
- 我发现的IT大牛的优秀博客
- 面试笔试杂项积累-leetcode 246-260
- Logistic Regression
- DP入门之数塔(2084)
- 如何向外行解释产品经理频繁更改需求为什么会令程序员烦恼?
- 文章标题
- 数据库入门
- python、nodejs和java性能对比
- Educational Codeforces Round 7 CF622C Not Equal on a Segment
- 数据库操作