# 微软等数据结构+算法面试100题全部答案集锦【下】

2016.01.25 15:28 18644浏览

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

Have done this.

71.数值的整数次方。

double Power(double base, int exponent)
{
double result = 1.0;
for(int i = 1; i <= exponent; ++i)
result *= base;
return result;
}

double power(double base, int exp) {
if (exp == 1) return base;
double half = power(base, exp >> 1);
return (((exp & 1) == 1) ? base : 1.0) half half;
}

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.
public class Singleton {
private static Singleton instance = new Singleton();
private synchronized Singleton() {
}
public Singleton getInstance() {
return instance();
}
}
This may not be correct. I’m quite bad at this...

73.对策字符串的最大长度。

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.数组中超过出现次数超过一半的数字

Delete every two different digits. The last one that left is the one.
int getMajor(int a[], int n) {
int x, cnt=0;
for (int i=0; i<n; i++) {
if (cnt == 0) {
x = a[i]; cnt++;
} else if (a[i]==x) {
cnt ++;
} else {
cnt --;
}
}
return x;
}

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

struct TreeNode
{
int m_nvalue;
TreeNode m_pLeft;
TreeNode
m_pRight;
};

Have done this. Do it again for memory...
TreeNode getLCA(TreeNode root, TreeNode X, TreeNode Y) {
if (root == NULL) return NULL;
if (X == root || Y == root) return root;
TreeNode left = getLCA(root->m_pLeft, X, Y);
TreeNode
right = getLCA(root->m_pRight, X, Y);
if (left == NULL) return right;
else if (right == NULL) return left;
else return root;
}

76.复杂链表的复制

struct ComplexNode
{
int m_nValue;
ComplexNode m_pNext;
ComplexNode
m_pSibling;
};

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.

if (pHead == NULL) return NULL;
}

ComplexNode
p = new ComplexNode();
}

ComplexNode
pSib = pNew->m_pNext;
if (pSib == NULL) { pNew->m_pSibling = NULL; }
else { pNew->m_pSibling = pSib->m_pSibling; }
}

ComplexNode
pSib = pNew->m_pNext;
} else {
pNew->pNext = NULL;
}
return pNew;
}

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.

3. 1.编写实现链表排序的一种算法。说明为什么你会选择用这样的方法？
For linked list sorting, usually mergesort is the best choice. Pros: O(1) auxilary space, compared to array merge sort. No node creation, just pointer operations.
}

Node mergeSort(Node p, int len) {
if (len == 1) { p->next = NULL; return p; }
Node pmid = p;
for (int i=0; i<len/2; i++) {
pmid = pmid->next;
}
Node
p1 = mergeSort(p, len/2);
Node p2 = mergeSort(pmid, len - len/2);
return merge(p1, p2);
}
Node
merge(Node p1, Node p2) {
Node p = NULL, ph = NULL;
while (p1!=NULL && p2!=NULL) {
if (p1->data<p2->data) {
if (ph == NULL) {ph = p = p1;}
else { p->next = p1; p1 = p1->next; p = p->next;}
} else {
if (ph == NULL) {ph = p = p2;}
else { p->next = p2; p2 = p2->next; p = p->next;}
}
}
p->next = (p1==NULL) ? p2 : p1;
return ph;
}

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。
So we have ~10G data. It is unlikely to put them all into main memory. Anyway, calculate the hash of each line in the first round, at the second round calculate the hash of the reverse of the line and remembers only the line number pairs that the hashes of the two directions collides. The last round only test those lines.

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
void
memmove(void dest, const void src, size_t n) {
if (dest==NULL || src == NULL) error(“NULL pointers”);
byte psrc = (byte)src;
byte pdest = (byte)dest;
int step = 1;
if (dest < src + n) {
psrc = (byte)(src+n-1);
pdest = (byte
)(dest+n-1);
step = -1;
}
for (int i=0; i<n; i++) {
pdest = psrc;
pdest += step; psrc += step;
}
}

84.第4 组百度面试题
2010 年3 道百度面试题[相信，你懂其中的含金量]
1.a~z 包括大小写与0~9 组成的N 个数, 用最快的方式把其中重复的元素挑出来。
By fastest, so memory is not the problem, hash is the first choice. Or trie will do.
Both run in O(Size) time, where size is the total size of the imput.

2.已知一随机发生器，产生0 的概率是p，产生1 的概率是1-p，现在要你构造一个发生器，使得它构造0 和1 的概率均为1/2；构造一个发生器，使得它构造1、2、3 的概率均为1/3；...，构造一个发生器，使得它构造1、2、3、...n 的概率均为1/n，要求复杂度最低。
Run rand() twice, we got 00, 01, 10 or 11. If it’s 00 or 11, discard it, else output 0 for 01, 1 for 10.

Similarly, assume C(M, 2) >= n and C(M-1, 2) < n. Do M rand()’s and get a binary string of M length. Assign 1100...0 to 1, 1010...0 to 2, ...

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，有的话返回子字符串的个数。
int count_of_substr(const char str, const char sub) {
int count = 0;
char p = str;
int n = strlen(sub);
while (
p != ‘\0’ ) {
if (strncmp(p, sub, n) == 0) count ++;
p++;
}
return count;
}

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.

Node * array2Tree(int[] array) {
return helper(array, 0, n-1);
}

Node helper(int[] array, int start, int end) {
if (start > end) return NULL;
int m = start + (end-start)/2;
Node
root = new Node(array[m]);
root->left = helper(array, start, m-1);
root->right = helper(array, m+1, end);
return root;
}

87.
1.大整数数相乘的问题。（这是2002 年在一考研班上遇到的算法题）
Do overflow manually.
final static long mask = (1 << 31) - 1;
ArrayList<Integer> multiply(ArrayList <Integer> a, ArrayList<Integer> b) {
ArrayList<Integer> result = new ArrayList<Integer>(a.size()b.size()+1);
for (int i=0; i<a.size(); i++) {
multiply(b, a.get(i), i, result);
}
return result;
}
void multiply(ArrayList<Integer> x, int a, int base, ArrayList<Integer> result) {
if (a == 0) return;
long overflow = 0;
int i;
for (i=0; i<x.size(); i++) {
long tmp = x.get(i)
a + result.get(base+i) + overflow;
overflow = (tmp >> 31);
}
while (overflow != 0) {
long tmp = result.get(base+i) + overflow;
overflow = (tmp >> 31);
}
}

Have done this.

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

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

It’s like partition in quick sort. Just keep the non-
part stable.

int partitionStar(char a[]) {
int count = 0;
int i = a.length-1, j=a.length-1; // i for the cursor, j for the first non- char
while (i >= 0) {
if (a[i] != ‘
’) {
swap(a, i--, j--);
} else {
i--; count ++;
}
}
return count;
}

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

2.编码实现字符串转整型的函数（实现函数atoi 的功能），据说是神州数码笔试题。如将字符串”+123”123, ”-0123”-123, “123CS45”123, “123.45CS”123, “CS123.45”0
int atoi(const char a) {
if (
a==’+’) return atoi(a+1);
else if (a==’-’) return - atoi(a+1);
char
p = a;
int c = 0;
while (p >= ‘0’ && p <= ‘9’) {
c = c10 + (p - ‘0’);
}
return c;
}

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

4.删除字符串中的数字并压缩字符串。如字符串”abc123de4fg56”处理后变为”abcdefg”。注意空间和效率。（下面的算法只需要一次遍历，不需要开辟新空间，时间复杂度为O(N)）
Also partition, keep non-digit stable.
char partition(const char str) {
char i = str; // i for cursor, j for the first digit char;
char
j = str;
while (i != ‘\0’) {
if (
i > ‘9’ || i < ‘0’) {
j++ = i++;
} else {
i++;
}
}
*j = ‘\0’;
return str;
}

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]是不是升序排列
boolean isAscending(int a[]) {
return isAscending(a, 0);
}
boolean isAscending(int a[], int start) {
return start == a.length - 1 || isAscending(a, start+1);
}

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

char strcpy(char strDest, const char strSrc);

char
strcpy(char strDest, const char strSrc) {
if (strSrc == NULL) return NULL;
char i = strSrc, j = strDest;
while (i != ‘\0’) {
j++ = i++;
}
j = ‘\0’;
return strDest;
}
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...

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

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 公升的提捅，两只提捅形状上下都不均

5 to 3 => 2
2 to 3, remaining 1
5 to remaining 1 => 4

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 分钟）

30

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

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.一道关于飞机加油的问题，已知：

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

Pass。ok，微软面试全部100题答案至此完。

20人点赞

• 20
• 2
• 收藏
• 共同学习，写下你的评论

0/150