# 数据结构-100道练习题

1.把二元查找树转变成排序的双向链表

10
/
6 14
/ \ /
4 8 12 16

4=6=8=10=12=14=16。

2.设计包含min 函数的栈。

Stack is a LIFO data structure. When some element is popped from the stack, the status will recover to the original status as before that element was pushed. So we can recover the minimum element, too.

3.求子数组的最大和

A traditional greedy approach.
Keep current sum, slide from left to right, when sum < 0, reset sum to 0.

4.在二元树中找出和为某一值的所有路径

10
/
5 12
/
4 7

5.查找最小的k 个元素

This is a very traditional question…

【0，1，2，3，4，5，6，7，8，9】

0 在下排出现了6 次，1 在下排出现了2 次，
2 在下排出现了1 次，3 在下排出现了0 次….

I don’t like brain teasers. Will skip most of them…

1.如果链表可能有环列?
2.如果需要求出俩个链表相交的第一个节点列?

1.有两个房间，一间房里有三盏灯，另一间房有控制着三盏灯的三个开关，

Skip.

2.你让一些人为你工作了七天，你要用一根金条作为报酬。金条被分成七小块，每天给出一

1+2+4;

1. ★用一种算法来颠倒一个链接表的顺序。现在在不用递归式的情况下做一遍。

★用一种算法在一个循环的链接表里插入一个节点，但不得穿越链接表。
I don’t understand what is “Chuanyue”.
★用一种算法整理一个数组。你为什么选择这种方法?
What is “Zhengli?”
★用一种算法使通用字符串相匹配。
What is “Tongyongzifuchuan”… a string with “*” and “?”? If so, here is the code.

★颠倒一个字符串。优化速度。优化空间。

★颠倒一个句子中的词的顺序，比如将“我叫克丽丝”转换为“克丽丝叫我”，

Reverse the whole string, then reverse each word. Using the reverseFixlen() above.

★找到一个子字符串。优化速度。优化空间。
KMP? BM? Sunday? Using BM or sunday, if it’s ASCII string, then it’s easy to fast access the auxiliary array. Otherwise an hashmap or bst may be needed. Lets assume it’s an ASCII string.

★比较两个字符串，用O(n)时间和恒量空间。
What is “comparing two strings”? Just normal string comparison? The natural way use O(n) time and O(1) space.

★假设你有一个用1001 个整数组成的数组，这些整数是任意排列的，但是你知道所有的整数都在1 到1000(包括1000)之间。此外，除一个数字出现两次外，其他所有数字只出现一次。假设你只能对这个数组做一次处理，用一种算法找出重复的那个数字。如果你在运算中使用了辅助的存储方式，那么你能找到不用这种方式的算法吗?
Sum up all the numbers, then subtract the sum from 1001*1002/2.
Another way, use A XOR A XOR B = B:

★不用乘法或加法增加8 倍。现在用同样的方法增加7 倍。

8
/
6 10
/ \ /
5 7 9 11

This is an interesting one. There is a traditional question that requires the binary tree to be re-constructed from mid/post/pre order results. This seems similar. For the problems related to (binary) trees, recursion is the first choice.
In this problem, we know in post-order results, the last number should be the root. So we have known the root of the BST is 8 in the example. So we can split the array by the root.

Already done this. Skipped.

This is interesting… Also recursively, the longest distance between two nodes must be either from root to one leaf, or between two leafs. For the former case, it’s the tree height. For the latter case, it should be the sum of the heights of left and right subtrees of the two leaves’ most least ancestor.
The first case is also the sum the heights of subtrees, just the height + 0.

（A?B:C）。
1+..+n=n*(n+1)/2=(n^2+n)/2
it is easy to get x/2, so the problem is to get n^2
though no if/else is allowed, we can easilly Go around using short-pass.
using macro to make it fancier:

Use two cursors. One at front and the other at the end. Keep track of the sum by moving the cursors.

8
/
6 10
/\ /
5 7 9 11

8
/
10 6
/\ /
11 9 7 5

struct BSTreeNode // a node in the binary search tree (BST)

8
/
6 10
/ \ /
5 7 9 11

The nodes in the levels are printed in the similar manner their parents were printed. So it should be an FIFO queue to hold the level. I really don’t remember the function name of the stl queue, so I will write it in Java…

Again, this depends on what is “char”. Let’s assume it as ASCII.

July：我想，这个题目，不少人已经见识过了。
Actually, although this is a so traditional problem, I was always to lazy to think about this or even to search for the answer.(What a shame…). Finally, by google I found the elegant solution for it.
The keys are:

1) if we shift the ids by k, namely, start from k instead of 0, we should add the result by k%n
2) after the first round, we start from k+1 ( possibly % n) with n-1 elements, that is equal to an (n-1) problem while start from (k+1)th element instead of 0, so the answer is (f(n-1, m)+k+1)%n
3) k = m-1, so f(n,m)=(f(n-1,m)+m)%n.
finally, f(1, m) = 0;
Now this is a O(n) solution.
int joseph(int n, int m) {
int fn=0;
for (int i=2; i<=n; i++) {
fn = (fn+m)%i; }
return fn;
}

/ 0 n=0
f(n)= 1 n=1
\ f(n-1)+f(n-2) n=2

This is the traditional problem of application of mathematics…

This question checks how the interviewee is familiar with C/C++? I’m so bad at C/C++…

2010 年中兴面试题

This is a combination generation problem.

I dont’ like brain teaser. As an AI problem, it seems impossible to write the solution in 20 min…

It seems that a brute-force edge cutting strategy could do. Enumerate all possibilities, then for each guy delete the permutation that could be reduced if failed (for A, B, C at 1st round), Then there should be only one or one group of choices left.

But who uses this as an interview question?

3D 坐标系原点(0.0,0.0,0.0)

4 个角坐标;
1:(., 0.0, .)
2:(., 0.0, .)
3:(., 0.0, .)
4:(., 0.0, .)
Crap… I totally cannot understand this problem… Does the . represent any possible number?

（1）.单链表就地逆置，
（2）合并链表

What do you mean by merge? Are the original lists sorted and need to be kept sorted? If not, are there any special requirements?
I will only do the sorted merging.

outputstr 所指的值为123456789

26.左旋转字符串

Have done it. Using reverse word function above.

27.跳台阶问题

f(n)=f(n-1)+f(n-2), f(1)=1, f(2)=2, let f(0) = 1, then f(n) = fibo(n-1);

28.整数的二进制表示中1 的个数

Traditional question. Use the equation xxxxxx10000 & (xxxxxx10000-1) = xxxxxx00000
Note: for negative numbers, this also hold, even with 100000000 where the “-1” leading to an underflow.

29.栈的push、pop 序列

push 1，push 2，push 3，push 4，pop，push 5，pop，pop，pop，pop，

This seems interesting. However, a quite straightforward and promising way is to actually build the stack and check whether the pop action can be achieved.

30.在从1 到n 的正数中1 出现的次数

This is complicated… I hate it…
Suppose we have N=ABCDEFG.

31.华为面试题：

Not clear problem. Skipped. Seems a Dijkstra could do.

int dij

32.

If only one swap can be taken, it is a O(n^2) searching problem, which can be reduced to O(nlogn) by sorting the arrays and doing binary search.
If any times of swaps can be performed, this is a double combinatorial problem.
In the book <>, a similar problem splits an array to halves as even as possible. It is possible to take binary search, when SUM of the array is not too high. Else this is a quite time consuming brute force problem. I cannot figure out a reasonable solution.

33.

Not a clear problem. Seems a bitset can do.

34.

I don’t know multithread programming at all….

35.

1 2 0 3 4
2 3 4 5 1
1 1 5 3 0

4 5
5 3

36.引用自网友：longzuo

n 支队伍比赛，分别编号为0，1，2。。。。n-1，已知它们之间的实力对比关系，

This question is like no-copying merge, or in place matrix rotation.

• No-copying merge: merge order to result, then merge the first half from order, and so on.
• in place matrix rotation: rotate 01, 23, .. , 2k/2k+1 to 02…2k, 1,3,…2k+1…
The two approaches are both complicated. However, notice one special feature that the losers’ order doesn’t matter. Thus a half-way merge is much simpler and easier:

37.

This is identical to the problem to find the longest acylic path in a directed graph. If there is a cycle, return false.
Firstly, build the graph. Then search the graph for the longest path.

Time complexity analysis:

38.

1.用天平（只能比较，不能称重）从一堆小球中找出其中唯一一个较轻的，使用x 次天平，

x=1, y=3: if a=b, c is the lighter, else the lighter is the lighter…
do this recursively. so y=3^x;

2.有一个很大很大的输入流，大到没有存储器可以将其存储下来，

That is, keep total number count N. If N<=m, just keep it.
For N>m, generate a random number R=rand(N) in [0, N), replace a[R] with new number if R falls in [0, m).

3.大量的URL 字符串，如何从中去除重复的，优化时间空间复杂度

1. Use hash map if there is enough memory.
2. If there is no enough memory, use hash to put urls to bins, and do it until we can fit the bin into memory.

39.

(1).

Have done this.
(2).

Do dfs, record low[i] as the lowest vertex that can be reached from i and i’s successor nodes. For each edge i, if low[i] = i and i is not a leaf in dfs tree, then i is a cut point. The other case is the root of dfs, if root has two or more children ,it is a cut point.

40.百度研发笔试题

1)设计一个栈结构，满足一下条件：min，push，pop 操作的时间复杂度为O(1)。
Have done this.

2)一串首尾相连的珠子(m 个)，有N 种颜色(N<=10)，

Use a sliding window and a counting array, plus a counter which monitors the num of zero slots in counting array. When there is still zero slot(s), advance the window head, until there is no zero slot. Then shrink the window until a slot comes zero. Then one candidate segment of (window_size + 1) is achieved. Repeat this. It is O(n) algorithm since each item is swallowed and left behind only once, and either operation is in constant time.

3)设计一个系统处理词语搭配问题，比如说中国和人民可以搭配，

41.求固晶机的晶元查找程序

Dont understand.

42.请修改append 函数，利用这个函数实现：

I don’t quite understand what it means by “not modifying linked list’s data”. If some nodes will be given up, it is weird for this requirement.

43.递归和非递归俩种方法实现二叉树的前序遍历。

44.腾讯面试题：
1.设计一个魔方（六面）的程序。
This is a problem to test OOP.
The object MagicCube must have following features

1) holds current status
2) easily doing transform
3) judge whether the final status is achieved
4) to test, it can be initialized
5) output current status

2.有一千万条短信，有重复，以文本文件的形式保存，一行一条，有重复。

10M msgs, each at most 140 chars, that’s 1.4G, which can fit to memory.
So use hash map to accumulate occurrence counts.
Then use a heap to pick maximum 10.

3.收藏了1 万条url，现在给你一条url，如何找出相似的url。（面试官不解释何为相似）
What a SB interviewer… The company name should be claimed and if I met such a interviewer, I will contest to HR. The purpose of interview is to see the ability of communication. This is kind of single side shutdown of information exchange.
My first answer will be doing edit distance to the url and every candidate. Then it depends on what interviewer will React. Other options includes: fingerprints, tries…

45.雅虎：
1.对于一个整数矩阵，存在一种运算，对矩阵中任意元素加一时，需要其相邻（上下左右）

A assignment problem. Two ways to solve. 1: duplicate each cell to as many as its value, do Hungarian algorithm. Denote the sum of the matrix as M, the edge number is 2M, so the complexity is 2MM; 2: standard maximum flow. If the size of matrix is NxN, then the algorithm using Ford Fulkerson algorithm is MNN.
too complex… I will do this when I have time…

2.一个整数数组，长度为n，将其分为m 份，使各份的和相等，求m 的最大值

{3,6}{2,4,3} m=2
{3,3}{2,4}{6} m=3 所以m 的最大值为3
Two restrictions on m, 1) 1 <= m <= n; 2) Sum(array) mod m = 0
NOTE: no hint that a[i]>0, so m could be larger than sum/max;
So firstly prepare the candidates, then do a brute force search on possible m’s.
In the search , a DP is available, since if f(array, m) = OR_i( f(array-subset(i), m) ), where Sum(subset(i)) = m.

Please do edge cutting yourself, I’m quite enough of this…

46.搜狐：

Suppose k parenthesis has f(k) permutations, k is large enough. Check the first parenthesis, if there are i parenthesis in it then, the number of permutations inside it and out of it are f(i) and f(k-i-1), respectively. That is

47.创新工场：

4，3，2}
Scan from left to right, maintain a decreasing sequence. For each number, binary search in the decreasing sequence to see whether it can be substituted.

48.微软：

The key is that, from the middle point of the array, half of the array is sorted, and the other half is a half-size shifted sorted array. So this can also be done recursively like a binary search.

49.一道看上去很吓人的算法面试题：

So a comparison sort is not allowed. Counting sort’s space complexity is O(n).
More ideas must be exchanged to find more conditions, else this is a crap.

50.网易有道笔试：
1.求一个二叉树中任意两个节点间的最大距离，两个节点的距离的定义是这两个节点间边

Have done this before.

2.求一个有向连通图的割点，割点的定义是，

Have done this before.
——————————————————————-
51.和为n 连续正数序列。

It seems that this can be solved by factorization. However, factorization of large n is impractical!

52.二元树的深度。

10
/
6 14
/ /
4 12 16

Have done this.

53.字符串的排列。

abc、acb、bac、bca、cab 和cba。

Full permutation generation. I will use another technique that swap two neighboring characters each time. It seems that all the characters are different. I need to think about how to do it when duplications is allowed. Maybe simple recursion is better for that.

54.调整数组顺序使奇数位于偶数前面。

This problem makes me recall the process of partition in quick sort.

1. 题目：类CMyString 的声明如下：
2. 最长公共字串。
题目：如果字符串一的所有字符按其在字符串中的顺序出现在另外一个字符串二中，
则字符串一称之为字符串二的子串。
注意，并不要求子串（字符串一）的字符必须连续出现在字符串二中。
请编写一个函数，输入两个字符串，求它们的最长公共子串，并打印出最长公共子串。
例如：输入两个字符串BDCABA 和ABCBDAB，字符串BCBA 和BDAB 都是是它们的最长公共子串，则输出它们的长度4，并打印任意一个子串。
分析：求最长公共子串（Longest Common Subsequence, LCS）是一道非常经典的动态规划
题，因此一些重视算法的公司像MicroStrategy 都把它当作面试题。
Standard DP…
3. 用俩个栈实现队列。
题目：某队列的声明如下： 分析：从上面的类的声明中，我们发现在队列中有两个栈。
因此这道题实质上是要求我们用两个栈来实现一个队列。
相信大家对栈和队列的基本性质都非常了解了：栈是一种后入先出的数据容器，
因此对队列进行的插入和删除操作都是在栈顶上进行；队列是一种先入先出的数据容器，
我们总是把新元素插入到队列的尾部，而从队列的头部删除元素。
4. 从尾到头输出链表。
题目：输入一个链表的头结点，从尾到头反过来输出每个结点的值。链表结点定义如下： 分析：这是一道很有意思的面试题。
该题以及它的变体经常出现在各大公司的面试、笔试题中。

59.不能被继承的类。

I don’t know c++.
Maybe it can be done by implement an empty private default constructor.

60.在O（1）时间内删除链表结点。

struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};

void DeleteNode(ListNode* pListHead, ListNode* pToBeDeleted);

Copy the data from tobedeleted’s next to tobedeleted. then delete tobedeleted. The special case is tobedelete is the tail, then we must iterate to find its predecessor.
The amortized time complexity is O(1).

————————————————————————-
61.找出数组中两个只出现一次的数字

XOR.

62.找出链表的第一个公共结点。

Have done this.

63.在字符串中删除特定的字符。

Have done this? Use a byte array / character hash to record second string. then use two pointers to shrink the 1st string.

1. 寻找丑数。
题目：我们把只包含因子2、3 和5 的数称作丑数（Ugly Number）。例如6、8 都是丑数，
但14 不是，因为它包含因子7。习惯上我们把1 当做是第一个丑数。求按从小到大的顺序的第1500 个丑数。
2. 输出1 到最大的N 位数
题目：输入数字n，按顺序输出从1 最大的n 位10 进制数。比如输入3，则输出1、2、3 一直到最大的3 位数即999。
分析：这是一道很有意思的题目。看起来很简单，其实里面却有不少的玄机。
So maybe n could exceed i32? I cannot tell where is the trick…
Who will output 2*10^9 numbers…
3. 颠倒栈。
题目：用递归颠倒一个栈。例如输入栈{1, 2, 3, 4, 5}，1 在栈顶。
颠倒之后的栈为{5, 4, 3, 2, 1}，5 处在栈顶。
Interesting…
4. 俩个闲玩娱乐。
5. 扑克牌的顺子
从扑克牌中随机抽5 张牌，判断是不是一个顺子，即这5 张牌是不是连续的。2-10 为数字本身，A 为1，J 为11，Q 为12，K 为13，而大小王可以看成任意数字。

2.n 个骰子的点数。把n 个骰子扔在地上，所有骰子朝上一面的点数之和为S。输入n，

All the possible values includes n to 6n. All the event number is 6^n.

68.把数组排成最小的数。

Actually this problem has little to do with algorithm…
The concern is, you must figure out how to arrange to achieve a smaller figure.
The answer is, if ab < ba, then a < b, and this is a total order.

69.旋转数组中的最小元素。

This is like the shifted array binary search problem. One blind point is that you may miss the part that the array is shifted by 0(or kN), that is not shifted.

70.给出一个函数来输出一个字符串的所有排列。

Have done this.

71.数值的整数次方。

1. 题目：设计一个类，我们只能生成该类的一个实例。
分析：只能生成一个实例的类是实现了Singleton 模式的类型。
I’m not good at multithread programming… But if we set a lazy initialization, the “if” condition could be interrupted thus multiple constructor could be called, so we must add synchronized to the if judgements, which is a loss of efficiency. Putting it to the static initialization will guarantee that the constructor only be executed once by the Java class loader.
2. 对策字符串的最大长度。
分析：可能很多人都写过判断一个字符串是不是对称的函数，这个题目可以看成是该函数的
加强版。
Build a suffix tree of x and inverse(x), the longest anagram is naturally found.
Suffix tree can be built in O(n) time so this is a linear time solution.

74.数组中超过出现次数超过一半的数字

75.二叉树两个结点的最低共同父结点

76.复杂链表的复制

Have heard this before, never seriously thought it.

The trick is like this: take use of the old pSibling, make it points to the new created cloned node, while make the new cloned node’s pNext backup the old pSibling.

77.关于链表问题的面试题目如下：
1.给定单链表，检测是否有环。

4.只给定单链表中某个结点p(并非最后一个结点，即p->next!=NULL)指针，删除该结点。办法很简单，首先是放p 中数据,然后将p->next 的数据copy 入p 中，接下来删除p->next即可。
5.只给定单链表中某个结点p(非空结点)，在p 前面插入一个结点。办法与前者类似，首先分配一个结点q，将q 插入在p 后，接下来将p 中的数据copy 入q中，然后再将要插入的数据记录在p 中。

78.链表和数组的区别在哪里？

1. Besides the common staff, linked list is more abstract and array is usually a basic real world object. When mentioning “linked list”, it doesn’t matter how it is implemented, that is, as long as it supports “get data” and “get next”, it is a linked list. But almost all programming languages provides array as a basic data structure.
2. So array is more basic. You can implement a linked list in an array, but cannot in the other direction.

79.
1.编写实现链表排序的一种算法。说明为什么你会选择用这样的方法？

2.编写实现数组排序的一种算法。说明为什么你会选择用这样的方法？
Actually, it depends on the data. If arbitrary data is given in the array, I would choose quick sort. It is asy to implement, fast.

3.请编写能直接实现strstr()函数功能的代码。
Substring test? Have done this.

80.阿里巴巴一道笔试题

12 个高矮不同的人,排成两排,每排必须是从矮到高排列,而且第二排比对应的第一排的人

Must be
1 a b … …
c d e … …
c could be 2th to 7th ( has to be smaller than d, e… those 5 numbers),
so f(12) = 6 f(10) = 6* 5 f(8) = 30 * 4f(6) = 1203f(4) = 3602f(2) = 720

81.第1 组百度面试题
1.一个int 数组，里面数据无任何限制，要求求出所有这样的数a[i]，其左边的数都小于等于它，右边的数都大于等于它。能否只用一个额外数组和少量其它空间实现。
Sort the array to another array, compare it with the original array, all a[i] = b[i] are answers.

2.一个文件，内含一千万行字符串，每个字符串在1K 以内，要求找出所有相反的串对，如abc 和cba。

3.STL 的set 用什么实现的？为什么不用hash？
I don’t quite know. Only heard of that map in stl is implemented with red-black tree. One good thing over hash is that you don’t need to re-hash when data size grows.

82.第2 组百度面试题
1.给出两个集合A 和B，其中集合A={name}，

SQL? Not a good defined question.

2.给出一个文件，里面包含两个字段{url、size}，即url 为网址，size 为对应网址访问的次数

（说明：url 数据量很大，100 亿级以上）

1. shell: gawk ‘ /baidu/ { print $2 } ’ FILE 2. shell: gawk ‘ /baidu/ {print$2}’ FILE | sort -n -r

83.第3 组百度面试题
1.今年百度的一道题目

Have done this.
2.百度笔试题

//To my memory, usually memcpy doesn’t check overlap, memmove do

84.第4 组百度面试题
2010 年3 道百度面试题[相信，你懂其中的含金量]
1.az 包括大小写与09 组成的N 个数, 用最快的方式把其中重复的元素挑出来。

2.已知一随机发生器，产生0 的概率是p，产生1 的概率是1-p，现在要你构造一个发生器，使得它构造0 和1 的概率均为1/2；构造一个发生器，使得它构造1、2、3 的概率均为1/3；…，构造一个发生器，使得它构造1、2、3、…n 的概率均为1/n，要求复杂度最低。

3.有10 个文件，每个文件1G，

If there is no enough memory, do bucketing first. For each bucket calculate the frequency of each query and sort. Then combine all the frequencies with multiway mergesort.

85.又见字符串的问题
1.给出一个函数来复制两个字符串A 和B。字符串A 的后几个字节和字符串B 的前几个字节重叠。分析：记住，这种题目往往就是考你对边界的考虑情况。
Special case of memmove.

2.已知一个字符串，比如asderwsde,寻找其中的一个子字符串比如sde 的个数，如果没有返回0，有的话返回子字符串的个数。

Also recursive way works. Possible optimizations like Sunday algorithm or Rabin-Karp algorithm will do.

86.

This is the first question I’m given in a google interview.

87.
1.大整数数相乘的问题。（这是2002 年在一考研班上遇到的算法题）
Do overflow manually.

Have done this.

3.实现strstr 功能，即在父串中寻找子串首次出现的位置。
（笔试中常让面试者实现标准库中的一些函数）
Have done this.

88.2005 年11 月金山笔试题。编码完成下面的处理函数。

89.神州数码、华为、东软笔试题
1.2005 年11 月15 日华为软件研发笔试题。实现一单链表的逆转。
Have done this.

2.编码实现字符串转整型的函数（实现函数atoi 的功能），据说是神州数码笔试题。如将字符串”+123”123, ”-0123”-123, “123CS45”123, “123.45CS”123, “CS123.45”0

3.快速排序（东软喜欢考类似的算法填空题，又如堆排序的算法等）
Standard solution. Skip.

4.删除字符串中的数字并压缩字符串。如字符串”abc123de4fg56”处理后变为”abcdefg”。注意空间和效率。（下面的算法只需要一次遍历，不需要开辟新空间，时间复杂度为O(N)）

5.求两个串中的第一个最长子串（神州数码以前试题）。

Use suffix tree. The longest common substring is the longest prefix of the suffixes.
O(n) to build suffix tree. O(n) to find the lcs.

90.
1.不开辟用于交换数据的临时空间，如何完成字符串的逆序
(在技术一轮面试中，有些面试官会这样问)。
Two cursors.

2.删除串中指定的字符
（做此题时，千万不要开辟新空间，否则面试官可能认为你不适合做嵌入式开发）
Have done this.

3.判断单链表中是否存在环。
Have done this.

91
1.一道著名的毒酒问题

Have done this. 10 mices.

2.有趣的石头问题

Quick sort.

92.
1.多人排成一个队列,我们认为从低到高是正确的序列,但是总有部分人不遵守秩序。如果说,前面的人比后面的人高(两人身高一样认为是合适的), 那么我们就认为这两个人是一对“捣乱分子”,比如说,现在存在一个序列:
176, 178, 180, 170, 171

<176, 170>, <176, 171>, <178, 170>, <178, 171>, <180, 170>, <180, 171>,

The answer is the swap number of insertion sort. The straightforward method is to do insertion sort and accumulate the swap numbers, which is slow: O(n^2)

A sub-quadratic solution can be done by DP.

f(n) = f(n-1) + Index(n)
Index(n), which is to determine how many numbers is smaller than a[n] in a[0..n-1], can be done in log(n) time using BST with subtree size.

93.在一个int 数组里查找这样的数，它大于等于左侧所有数，小于等于右侧所有数。直观想法是用两个数组a、b。a[i]、b[i]分别保存从前到i 的最大的数和从后到i 的最小的数，一个解答：这需要两次遍历，然后再遍历一次原数组，将所有data[i]>=a[i-1]&&data[i]<=b[i]的data[i]找出即可。给出这个解答后，面试官有要求只能用一个辅助数组，且要求少遍历一次。
It is natural to improve the hint… just during the second traversal, do the range minimum and picking together. There is no need to store the range minimums.

94.微软笔试题

Firstly sort the array. Then do DP: for each a[i], update the length of the arithmetic sequences. That’s a O(n^3) solution. Each arithmetic sequence can be determined by the last item and the step size.

95.华为面试题
1 判断一字符串是不是对称的，如：abccba
Two cursors.

2.用递归的方法判断整数组a[N]是不是升序排列

96.08 年中兴校园招聘笔试题
1．编写strcpy 函数

char *strcpy(char *strDest, const char *strSrc);

Maybe you need to check if src and dest overlaps, then decide whether to copy from tail to head.

97.第1 组微软较简单的算法面试题
1.编写反转字符串的程序，要求优化速度、优化空间。
Have done this.

2.在链表里如何发现循环链接？
Have done this.

3.编写反转字符串的程序，要求优化速度、优化空间。
Have done this.

4.给出洗牌的一个算法，并将洗好的牌存储在一个整形数组里。
Have done this.

5.写一个函数，检查字符是否是整数，如果是，返回其整数值。
（或者：怎样只用4 行代码编写出一个从字符串到长整形的函数？）
Char or string?
have done atoi;

98.第2 组微软面试题
1.给出一个函数来输出一个字符串的所有排列。
Have done this…

2.请编写实现malloc()内存分配函数功能一样的代码。
Way too hard as an interview question…
Please check wikipedia for solutions…

3.给出一个函数来复制两个字符串A 和B。字符串A 的后几个字节和字符串B 的前几个字节重叠。
Copy from tail to head.

4.怎样编写一个程序，把一个有序整数数组放到二叉树中？
Have done this.

5.怎样从顶部开始逐层打印二叉树结点数据？请编程。
Have done this…

6.怎样把一个链表掉个顺序（也就是反序，注意链表的边界条件并考虑空链表）？
Have done this…

99.第3 组微软面试题
1.烧一根不均匀的绳，从头烧到尾总共需要1 个小时。现在有若干条材质相同的绳子，问如何用烧绳的方法来计时一个小时十五分钟呢？
May have done this… burn from both side gives ½ hour.

2.你有一桶果冻，其中有黄色、绿色、红色三种，闭上眼睛抓取同种颜色的两个。抓取多少个就可以确定你肯定有两个同一颜色的果冻？（5 秒-1 分钟）
4.

3.如果你有无穷多的水，一个3 公升的提捅，一个5 公升的提捅，两只提捅形状上下都不均

Seems there are too many answers.
I will pick anyone to ask: how to get to your country? Then pick the other way.

100.第4 组微软面试题，挑战思维极限
1.12 个球一个天平，现知道只有一个和其它的重量不同，问怎样称才能用三次就找到那个

Too complicated. Go find brain teaser answers by yourself.

2.在9 个点上画10 条直线，要求每条直线上至少有三个点？（3 分钟-20 分钟）

3.在一天的24 小时之中，时钟的时针、分针和秒针完全重合在一起的时候有几次？都分别是什么时间？你怎样算出来的？（5 分钟-15 分钟）

1.第一题. 五个海盗抢到了100 颗宝石，每一颗都一样大小和价值连城。他们决定这么分：

A traditional brain teaser.
Consider #5, whatever #4 proposes, he won’t agree, so #4 must agree whatever #3 proposes. So if there are only #3-5, #3 should propose (100, 0, 0). So the expected income of #3 is 100, and #4 and #5 is 0 for 3 guy problem. So whatever #2 proposes, #3 won’t agree, but if #2 give #4 and #5 $1, they can get more than 3-guy subproblem. So #2 will propose (98, 0, 1, 1). So for #1, if give #2 less than$98, #2 won’t agree. But he can give #3 $1 and #4 or #5$2, so this is a (97, 0, 1, 2, 0) solution.

2.一道关于飞机加油的问题，已知：

（所有飞机从同一机场起飞，而且必须安全返回机场，不允许中途降落，中间没有飞机场）

• 版权声明： 本博客所有文章，未经许可，任何单位及个人不得做营利性使用！转载请标明出处！如有侵权请联系作者。