面试笔试杂项积累-leetcode 171-175
2016-02-08 22:38
465 查看
171.171-Excel Sheet Column Number-Difficulty: Easy
Related to questionExcel Sheet Column Title
Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28
思路
与168题恰好相反public class Solution {
public int TitleToNumber(string s) {
int anwser = 0;
for (int i = 0; i < s.Length; i++)
{
anwser += (s[i] - 64) * (int)Math.Pow(26, s.Length - i - 1);
}
return anwser;
}
}
172.172-Factorial Trailing Zeroes-Difficulty: Easy
Given an integer n, return the number of trailing zeroes in n!.Note: Your solution should be in logarithmic time complexity.
思路
对n!做质因数分解n!=2x*3y*5z*...
显然0的个数等于min(x,z),并且min(x,z)==z
证明:
对于阶乘而言,也就是1*2*3*...*n
[n/k]代表1~n中能被k整除的个数
那么很显然
[n/2] > [n/5] (左边是逢2增1,右边是逢5增1)
[n/2^2] > [n/5^2](左边是逢4增1,右边是逢25增1)
……
[n/2^p] > [n/5^p](左边是逢2^p增1,右边是逢5^p增1)
随着幂次p的上升,出现2^p的概率会远大于出现5^p的概率。
因此左边的加和一定大于右边的加和,也就是n!质因数分解中,2的次幂一定大于5的次幂
参考: http://www.cnblogs.com/ganganloveu/p/4193373.html
public class Solution { public int TrailingZeroes(int n) { int ret = 0; while(n!=0) { ret += n /= 5; } return ret; } }
173.173-Binary Search Tree Iterator-Difficulty: Medium
mplement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.Calling
next()will return the next smallest number in the BST.
Note:
next()and
hasNext()should run in average O(1) time and uses O(h) memory, where
h is the height of the tree.
思路
对二叉搜索树进行design,next()返回下一个最小值
使用栈来解决
参考:
https://leetcode.com/discuss/78858/my-solution-with-less-than-10-lines-of-code
/**
* Definition for binary tree
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class BSTIterator {
Stack<TreeNode> stack = new Stack<TreeNode>();
public BSTIterator(TreeNode root)
{
pushAll(root);
}
/** @return whether we have a next smallest number */
public bool HasNext()
{
return stack.Count > 0 ? true : false;
}
/** @return the next smallest number */
public int Next()
{
TreeNode temp = stack.Pop();
pushAll(temp.right);
return temp.val;
}
public void pushAll(TreeNode root)
{
while (root != null)
{
stack.Push(root);
root = root.left;
}
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.HasNext()) v[f()] = i.Next();
*/
相关文章推荐
- 面试笔试杂项积累-leetcode 166-170
- C printf() 详解——printf('%08x',number); 程序员面试宝典中的一个错误 char * b=(char *)&a
- 程序员到底是一个什么职业?
- 面试笔试杂项积累-leetcode 161-165
- 面试笔试杂项积累-leetcode 156-160
- 面试笔试杂项积累-leetcode 151-155
- 面试笔试杂项积累-leetcode 146-150
- 优雅程序员的成长历程
- 大数据时代的程序员
- 黑马程序员-学习日记09
- 黑马程序员-学习日记08
- 黑马程序员-学习日记06
- 黑马程序员-学习日记05
- 黑马程序员-学习日记04
- 黑马程序员-学习日记-03
- 黑马程序员-学习日志02
- 黑马程序员-学习日志01
- 国内大型门户网站iOS面试题
- 国内搜索老大iOS面试题
- 国内在线旅游巨头iOS面试题