您的位置:首页 > 职场人生

面试笔试杂项积累-leetcode 171-175

2016-02-08 22:38 465 查看

171.171-Excel Sheet Column Number-Difficulty: Easy

Related to question
Excel 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();
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: