随笔- 509
文章- 0
评论- 151
阅读-
22万
03 2014 档案
《Cracking the Coding Interview》——第11章:排序和搜索——题目8
摘要:2014-03-21 22:23题目:假设你一开始有一个空数组,你在读入一些整数并将其插入到数组中,保证插入之后数组一直按升序排列。在读入的过程中,你还可以进行一种操作:查询某个值val是否存在于数组中,并给出这个元素在数组中的位置(如果有多个的重复元素话,给出最小的下标)。解法:书上的原题不是这么描述的,但我觉得用这种插入排序的说法更好理解。虽然说是数组,但实际上既可以用真的数组来模拟这一过程,也可以用一棵二叉搜索树来做。我的实现是用二叉搜索树,每个节点里除了记录元素的值之外,还记录它的左子树有多少个点。这样在树里面也能进行对数级的查找。其实,用数组直接模拟的话,代码应该更好写的。代码: 1
阅读全文
《Cracking the Coding Interview》——第11章:排序和搜索——题目7
摘要:2014-03-21 22:05题目:给你N个盒子堆成一座塔,要求下面盒子的长和宽都要严格大于上面的。问最多能堆多少个盒子?解法1:O(n^2)的动态规划解决。其实是最长递增子序列问题,所以也可以用O(n * log(n))的优化算法。代码:// 11.7 n boxes are to stack up to a tower. Every box must be strictly smaller in width and height than the one right below it.// How many boxes at most can you stack up?#include
阅读全文
《Cracking the Coding Interview》——第11章:排序和搜索——题目6
摘要:2014-03-21 21:50题目:给定一个MxN的二位数组,如果每一行每一列都是升序排列(不代表全展开成一个一维数组仍是升序排列的)。请设计一个算法在其中查找元素。解法:对于这么一个数组,有两点是确定的:1. 左上最小,右下最大;2. 左边不大于右边,上边不大于下边。根据这么个思路,你可以从左下或者右上开始查找,应该向左走向右走,还是向上走向下走,你懂的。用这种方法,可以在线性的时间内找出一个元素。代码: 1 // 11.6 Given an MxN matrix, each row and each column is sorted in ascending order. 2 // Fo
阅读全文
《Cracking the Coding Interview》——第11章:排序和搜索——题目5
摘要:2014-03-21 21:37题目:给定一个字符串数组,但是其中夹杂了很多空串“”,不如{“Hello”, “”, “World”, “”, “”, “”, “Zoo”, “”}请设计一个算法在其中查找字符串。解法:要么一次性将其中夹杂的空串去掉,要么在二分查找的过程中逐个跳过空串。反正整体思路仍是二分。代码: 1 // 11.5 Given an array of strings interspersed with empty string ""s. Find out if a target string exists in the string. 2 #include
阅读全文
《Cracking the Coding Interview》——第11章:排序和搜索——题目4
摘要:2014-03-21 21:28题目:给定一个20GB大小的文本文件,每一行都是一个字符串。请设计方法将这个文件里的字符串排序。解法:请看下面的注释。代码: 1 // 11.4 Given a file of 20GB containing strings, one word each line. How would you sort them all? 2 // Answer: 3 // 1. Split them into 200M pieces. 4 // 2. For each pieces, use comparison sort or hashing to sort i...
阅读全文
《Cracking the Coding Interview》——第11章:排序和搜索——题目3
摘要:2014-03-21 20:55题目:给定一个旋转过的升序排序好的数组,不知道旋转了几位。找出其中是否存在某一个值。解法1:如果数组的元素都不重复,那么我的解法是先找出旋转的偏移量,然后进行带偏移量的二分搜索。两个过程都是对数级的。代码: 1 // 11.3 Given a sorted array rotated by a few positions, find out if a value exists in the array. 2 // Suppose all elements in the array are unique. 3 #include 4 #include 5 #in..
阅读全文
《Cracking the Coding Interview》——第11章:排序和搜索——题目2
摘要:2014-03-21 20:49题目:设计一种排序算法,使得anagram排在一起。解法:自定义一个comparator,使用额外的空间来统计字母个数,然后比较字母个数。代码: 1 // 11.2 Sort an array of strings such that anagrams stay next to each other. 2 #include 3 #include 4 #include 5 #include 6 using namespace std; 7 8 string ta, tb; 9 int counting[256];10 11 void countingSo...
阅读全文
《Cracking the Coding Interview》——第11章:排序和搜索——题目1
摘要:2014-03-21 20:35题目:给定已升序排列的数组A和数组B,如果A有足够的额外空间容纳A和B,请讲B数组合入到A中。解法:由后往前进行归并。代码: 1 // 11.1 Given two sorted array A and B, suppose A is large enough to hold them both. Merge B into A. 2 #include 3 #include 4 using namespace std; 5 6 void mergeBIntoA(int a[], int b[], int na, int nb) 7 { 8 if (n...
阅读全文
《Cracking the Coding Interview》——第9章:递归和动态规划——题目11
摘要:2014-03-21 20:20题目:给定一个只包含‘0’、‘1’、‘|’、‘&’、‘^’的布尔表达式,和一个期望的结果(0或者1)。如果允许你用自由地给这个表达式加括号来控制运算的顺序,问问有多少种加括号的方法来达到期望的结果值。解法:DFS暴力解决,至于优化方法,应该是可以进行一部分剪枝的,但我...
阅读全文
《Cracking the Coding Interview》——第9章:递归和动态规划——题目10
摘要:2014-03-20 04:15题目:你有n个盒子,用这n个盒子堆成一个塔,要求下面的盒子必须在长宽高上都严格大于上面的。如果你不能旋转盒子变换长宽高,这座塔最高能堆多高?解法:首先将n个盒子按照长宽高顺序排好序,然后动态规划,我写了个O(n^2)时间复杂度的代码。代码: 1 // 9.10 A stack of n boxes is form a tower. where every stack must be strictly larger than the one right above it. 2 // The boxes cannot be rotated. 3 #include .
阅读全文
《Cracking the Coding Interview》——第9章:递归和动态规划——题目9
摘要:2014-03-20 04:08题目:八皇后问题。解法:DFS解决。代码: 1 // 9.9 Eight-Queen Problem, need I say more? 2 #include 3 #include 4 using namespace std; 5 6 class Solutio...
阅读全文
《Cracking the Coding Interview》——第9章:递归和动态规划——题目8
摘要:2014-03-20 04:04题目:给你不限量的1分钱、5分钱、10分钱、25分钱硬币,凑成n分钱总共有多少种方法?解法:理论上来说应该是有排列组合的公式解的,但推导起来太麻烦而且换个数据就又得重推了,所以我还是用动态规划解决。代码: 1 // 9.8 Given unlimited quarters(25 cents), dimes(10 cents), nickels(5 cents) and pennies(1 cent), how many ways are there to represent n cents. 2 #include 3 #include 4 using nam..
阅读全文
《Cracking the Coding Interview》——第9章:递归和动态规划——题目7
摘要:2014-03-20 03:35题目:实现画图的Flood Fill操作。解法:DFS和BFS皆可,但BFS使用的队列在时间复杂度上常数项比较大,速度略慢,所以我选了DFS。当然,如果图很大的话DFS是会导致call stack溢出的,那就摊上事儿了。代码: 1 // 9.7 Implement a flood fill painter that changes a certain area to a certain color. You are given one point as the seed. 2 #include 3 #include 4 using namespace std..
阅读全文
《Cracking the Coding Interview》——第9章:递归和动态规划——题目6
摘要:2014-03-20 03:27题目:输出所有由N对括号组成的合法的括号序列。比如n=2,“()()”、“(())”等等。解法:动态规划配合DFS,应该也叫记忆化搜索吧。一个整数N总可以拆成若干个正整数的和,执行搜索的时候也是按照这个规则,将N序列拆成多个子序列进行搜索,同时将中间的搜索结果记录下来,以便下次再搜到的时候直接调用,省掉重复计算的开销。代码: 1 // 9.6 Print all valid parentheses sequences of n ()s. 2 #include 3 #include 4 #include 5 using namespace std; 6 7...
阅读全文
《Cracking the Coding Interview》——第9章:递归和动态规划——题目5
摘要:2014-03-20 03:23题目:给定一个字符串,输出其全排列。解法:可以调用STL提供的next_permutation(),也可以自己写一个。对于这种看起来简单的题目,应该在能优化的地方,尽量想办法优化。在面试里如果大家都会做的题,你就得做的很好才能拉开差距,否则就等着thank you了。代码: 1 // 9.5 Print all permutations of a string. 2 #include 3 #include 4 #include 5 using namespace std; 6 7 void countingSort(char s[], int n) 8 ...
阅读全文
《Cracking the Coding Interview》——第9章:递归和动态规划——题目4
摘要:2014-03-20 03:08题目:给定一个集合,返回其幂集。解法:DFS。代码: 1 // 9.4 Return all subsets of a set 2 #include 3 #include 4 using namespace std; 5 6 void getSubsets(const vector &v, int idx, vector &buffer, vector > &res) 7 { 8 if (idx == (int)v.size()) { 9 res.push_back(buffer);10 } else {11 ...
阅读全文
《Cracking the Coding Interview》——第9章:递归和动态规划——题目3
摘要:2014-03-20 03:01题目:给定一个已按升序排序的数组,找出是否有A[i] = i的情况出现。解法1:如果元素不重复,是可以严格二分查找的。代码: 1 // 9.3 Given a unique sorted array, find a position where A[i] = i, if one exists. 2 #include 3 #include 4 using namespace std; 5 6 int main() 7 { 8 vector v; 9 int n;10 int i;11 int ll, rr, mm;12 ...
阅读全文
《Cracking the Coding Interview》——第9章:递归和动态规划——题目2
摘要:2014-03-20 02:55题目:从(0, 0)走到(x, y),其中x、y都是非负整数。每次只能向x或y轴的正方向走一格,那么总共有多少种走法。如果有些地方被障碍挡住不能走呢?解法1:如果没有障碍的话,组合数学,排列组合公式C(x + y, x)。代码: 1 // 9.2 How many ways are there to go from (0, 0) to (x, y), if you only go left or up, and one unit at a time? 2 #include 3 using namespace std; 4 5 int combination(..
阅读全文
《Cracking the Coding Interview》——第9章:递归和动态规划——题目1
摘要:2014-03-20 02:55题目:小朋友跳台阶,每次跳1层或2层,那么跳N层总共有多少种跳法。解法:斐波那契数列。代码: 1 // 9.1 A child can run up the stair with n staircases. Every time he can hop up by 1, 2 or 3 steps. How many possible way to do this are there? 2 #include 3 #include 4 using namespace std; 5 6 int main() 7 { 8 int n; 9 int i...
阅读全文
《Cracking the Coding Interview》——第7章:数学和概率论——题目7
摘要:2014-03-20 02:29题目:将质因数只有3, 5, 7的正整数从小到大排列,找出其中第K个。解法:用三个iterator指向3, 5, 7,每次将对应位置的数分别乘以3, 5, 7,取三者中最小的数作为生成的下一个结果。可以一次性生成整个序列,因为这个序列一般不会很长,增长率是指数级的。代码: 1 // 7.7 Find the kth number that has no prime factors other than 3, 5 or 7. 2 #include 3 #include 4 #include 5 using namespace std; 6 7 int ma...
阅读全文
《Cracking the Coding Interview》——第7章:数学和概率论——题目6
摘要:2014-03-20 02:24题目:给定二位平面上一堆点,找到一条直线,使其穿过的点数量最多。解法:我的解法只能适用整点,对于实数坐标就得换效率更低的办法了。请参见LeetCode -Max Points on a Line-zhuli19901106- 博客园。代码: 1 // 7.6 Find the line that crosses the most points. 2 #include 3 #include 4 using namespace std; 5 6 struct Point { 7 int x; 8 int y; 9 Po...
阅读全文
《Cracking the Coding Interview》——第7章:数学和概率论——题目5
摘要:2014-03-20 02:20题目:给定二维平面上两个正方形,用一条直线将俩方块划分成面积相等的两部分。解法:穿过对称中心的线会将面积等分,所以连接两个中心即可。如果两个中心恰好重合,那么任意穿过这个点的直线都满足条件。代码:1 // 7.5 Given two squares on two-dimensional plane, draw a line to cut them in two parts with equal area.2 // Answer:3 // Apparently the line should go through the center of the two ...
阅读全文
《Cracking the Coding Interview》——第7章:数学和概率论——题目4
摘要:2014-03-20 02:16题目:只用加法和赋值,实现减法、乘法、除法。解法:我只实现了整数范围内的。减法就是加上相反数。乘法就是连着加上很多个。除法就是减到不能减为止,数数总共减了多少个。代码: 1 // 7.4 Implement the -*/ function with only the + operator. 2 // You cannot use bit operation, although you might want it for efficiency. 3 #include 4 using namespace std; 5 6 int negate(in...
阅读全文
《Cracking the Coding Interview》——第7章:数学和概率论——题目3
摘要:2014-03-20 02:05题目:给定笛卡尔二维平面上两条直线,判断它们是否相交。解法:相交、重合、平行。代码: 1 // 7.3 Given two lines on the Cartesian, determine if they would intersect. 2 #include 3 using namespace std; 4 5 int main() 6 { 7 // a * x + b * y + c = 0; 8 // d * x + e * y + f = 0; 9 int a, b, c, d, e, f;10 bool suc;1...
阅读全文
《Cracking the Coding Interview》——第7章:数学和概率论——题目2
摘要:2014-03-20 01:59题目:有n只蚂蚁在正n边形的n个顶点,同时以同速率开始沿着边走。每只蚂蚁走的方向是随机的,那么这些蚂蚁至少有两只发生碰撞的概率是多少。解法:只有所有蚂蚁都往一个方向走才不会碰撞,所以不碰的概率就是2/2^n,碰的概率就用1减去喽。代码:1 // 7.2 n ants are standing on the vertices of an n-edged equilateral polygon, they start walking at the same time, same speed.2 // Every ant chooses randomly a dire
阅读全文
《Cracking the Coding Interview》——第7章:数学和概率论——题目1
摘要:2014-03-20 01:57题目:玩篮球投篮,有两种玩法:要么1投1中,要么3投两中。你单次投篮中的概率是p,那么对于不同的p,哪种玩法胜率更高?解法:第一种总是胜率更高,可以列不等式算算,结果发现是个恒不等式。代码: 1 // 7.1 Suppose you're playing a basketball game, you have two choices: 2 // A: one shot one hit 3 // B: three shots two hits 4 // For what probability of p would you choose A or B. 5
阅读全文
《Cracking the Coding Interview》——第6章:智力题——题目6
摘要:2014-03-20 01:14题目:有100栈灯,一开始都关着。如果你按照n从1~100的顺序,每次都掰一下n的倍数的开关(开->关,关->开),那么到最后有多少灯是亮的?解法:这个题目要多想想再动手,因为想通了以后就基本不用动手了。对于编号为x的灯,每当i是x的约数时,在第i轮时第x号灯就被掰了一次。比如6的约数为{1,2,3,6},6号灯被掰了4次。那么,每个灯被掰的次数就是约数个数次。约数个数的公式你懂的,但是用不着去算。如果一盏灯是开的,那么它就被掰了奇数次,根据约数和公式,只有因数分解之后所有指数都是偶数的时候,约数个数才为奇数。比如36的约数{1,2,3,4,6,9,
阅读全文
《Cracking the Coding Interview》——第6章:智力题——题目5
摘要:2014-03-20 01:08题目:扔鸡蛋问题。有一个鸡蛋,如果从N楼扔下去恰好会摔碎,低于N楼则不碎,可以继续扔。给你两个这样的鸡蛋,要求你一定得求出N,怎么扔才能减少最坏情况下的扔的次数?解法:为了让worst case得到最优化,就需要让best case和worst case最接近。具体做法请参见书上题解,因为我一直在想着二分,实在是摸不着头脑。代码: 1 // 6.5 Given 100 floors and 2 eggs. 2 // If the egg can sustain a dropping from nth floor, and will break for highe
阅读全文
《Cracking the Coding Interview》——第6章:智力题——题目4
摘要:2014-03-20 01:02题目:无力描述的一道智力题,真是货真价实的智力题,让我充分怀疑自己智力的智力题。有兴趣的还是看书去吧。解法:能把题目看懂,你就完成80%了,用反证法吧。代码: 1 // 6.4 There is an island with a bunch of people living there. 2 // The strange thing is, any blue-eyed tourists must leave immediately when they find out they're blue-eyed. 3 // Everyone can see ot
阅读全文
《Cracking the Coding Interview》——第6章:智力题——题目3
摘要:2014-03-20 00:48题目:有3升的瓶子和5升的瓶子,只允许倒满、倒到满为止、或是泼光三种操作,怎么搞出4升水呢?解法:如果A和B是互质的两个正整数,且A 5 using namespace std; 6 7 int gcd(int x, int y) 8 { 9 return x == 0 ? y : gcd(y % x, x);10 }11 12 int main()13 {14 int x, y;15 int vx, vy;16 int v;17 18 while (scanf("%d%d%d", &x, &y, &v) == ...
阅读全文
《Cracking the Coding Interview》——第6章:智力题——题目2
摘要:2014-03-19 06:57题目:对于8x8的棋盘,如果拿掉对角位置的两个小块儿,能否用1x2的多米诺牌拼成剩下的棋盘?解法:不可能。且不说8x8,NxN都是不可能的。如果N是奇数,NxN-2是奇数,自然不可能用偶数的面积拼成。如果N为偶数,根据小学学过的染色问题,将1x2的骨牌染成1黑1白,那么最后拼成的棋盘肯定有31黑31白。问题是,摘掉的两个对角位置的颜色是一样的,所以得出矛盾,也不可能完成。代码:1 // 6.2 There is an 8x8 chessboard, if we remove the two pieces at diagonal corners, can you
阅读全文
《Cracking the Coding Interview》——第6章:智力题——题目1
摘要:2014-03-19 06:40题目:有20瓶药,其中19瓶装的都是1.0克的药片,只有1瓶装了1.1克的药。给你一个能称出具体克数的电子秤,只允许你称一次,怎么找出那瓶不一样的?解法:如果药片管够,从每个瓶子里取出数量各不相同的药片,根据质量的总和减去“期望的”质量总和,就知道哪瓶有问题了。代码: 1 // 6.1 There are 20 bottles of pills, all of which have pills of 1g, except one with 1.1g. 2 // Given a balance that can provides exact measurement
阅读全文
《Cracking the Coding Interview》——第5章:位操作——题目8
摘要:2014-03-19 06:33题目:用一个byte数组来模拟WxH的屏幕,每个二进制位表示一个像素。请设计一个画水平线的函数。解法:一个点一个点地画就可以了。如果要优化的话,其实可以把中间整字节的部分一口气画了,只用1/8的力气。代码: 1 // 5.8 Given a byte array, set a consecutive bit segment to '1'. 2 #include 3 #include 4 using namespace std; 5 6 typedef unsigned char byte; 7 8 inline void setBit(vecto
阅读全文
《Cracking the Coding Interview》——第5章:位操作——题目7
摘要:2014-03-19 06:27题目:有一个数组里包含了0~n中除了某个整数m之外的所有整数,你要设法找出这个m。限制条件为每次你只能用O(1)的时间访问第i个元素的第j位二进制位。解法:0~n的求和有公式可循,只要把所有数都加起来就能知道缺少的m是几了。书本提供了一种比较高效的解法,我仔细读了以后觉得书上给的优化算法实际上需要额外的空间来支持,coding难度偏高,临场的话我估计挺难写出来的。代码: 1 // 5.7 Find the missing integer from 0 to n, you may only access one bit at a time. 2 #include
阅读全文
《Cracking the Coding Interview》——第5章:位操作——题目6
摘要:2014-03-19 06:24题目:将一个整数的奇偶二进制位交换,(0, 1) (2, 3) ...解法:使用掩码来进行快速交换,定义掩码为'0101...'和‘1010...’。代码: 1 // 5.6 Swap odd and even bits in an integer. 2 #include 3 using namespace std; 4 5 unsigned int swapBits(unsigned int n) 6 { 7 static const unsigned int mask[2] = {0x55555555, 0xaaaaaaaa}; 8 9...
阅读全文
《Cracking the Coding Interview》——第5章:位操作——题目5
摘要:2014-03-19 06:22题目:将整数A变成整数B,每次只能变一个二进制位,要变多少次呢。解法:异或,然后求‘1’的个数。代码: 1 // 5.5 Determine the number of bits required to convert integer A to B. 2 #include 3 using namespace std; 4 5 int numberOfOnes(unsigned int n) 6 { 7 int res = 0; 8 9 while (n != 0) {10 n = n & (n - 1);11 ...
阅读全文
《Cracking the Coding Interview》——第5章:位操作——题目4
摘要:2014-03-19 06:15题目:解释(n & (n - 1)) == 0是什么意思?解法:n&n-1是去掉最低位‘1’的方法。根据运算符优先级,貌似用不着加那个括号,但位运算的优先级总是个模棱两可的东西,所以一般还是要加上的。去掉一个‘1’就成了0,也就是说n是2的整次幂。代码: 1 // 5.4 Show what the code "n & (n - 1) == 0" means. 2 #include 3 using namespace std; 4 5 int main() 6 { 7 unsigned int n; 8 9 while
阅读全文
《Cracking the Coding Interview》——第5章:位操作——题目3
摘要:2014-03-19 05:57题目:给定一个整数N,求出比N大,而且二进制表示中和N有相同个数的‘1’的最小的数,比如3是‘11’,接下来的5是‘101’,再接下来的6是‘110’。解法:从低位往高位,首先跳过连续的‘0’,然后跳过连续的‘1’,并数数有多少个1。如果这时还没到最高位,那就从刚才跳过的‘1’中拿出1个放到这位上(当前位是‘0’),然后把剩下的‘1’填到最低的几位上去。中间填充‘0’。比如:‘100111000’的下一个是‘101000011’代码: 1 // 5.3 Find the next largest number that have same number of &
阅读全文
《Cracking the Coding Interview》——第5章:位操作——题目2
摘要:2014-03-19 05:47题目:给定一个double型浮点数,输出其二进制表示,如果不能在32个字符内完成输出,则输出“ERROR”。解法:如果你熟悉IEEE754标准,应该知道double和float型的二进制位里都是什么。double型最高位是符号位,随后11位是指数位,之后52位是尾数。你可以根据尾数和指数来判断要用多少二进制位才能精确表示这个浮点数。代码不怎么好写,这种题目应该也不常考吧。代码: 1 // 5.2 Given a double, print its binary representation if can be done in 32 characters. 2 #
阅读全文
《Cracking the Coding Interview》——第5章:位操作——题目1
摘要:2014-03-19 05:45题目:给定两个数M和N,将N按照二进制位,覆盖到M的特定段位中去。解法:位操作,请看代码。代码: 1 // 5.1 Insert one number into the certain bit segment of another number. 2 #include 3 using namespace std; 4 5 void printBinary(unsigned num) 6 { 7 unsigned bit = 1 >= 1;12 } while (bit);13 }14 15 unsigned insertBits(unsign...
阅读全文
《Cracking the Coding Interview》——第4章:树和图——题目9
摘要:2014-03-19 05:07题目:给定一棵二叉树T和一个值value,在T中找出所有加起来和等于value的路径。路径的起点和终点都可以是树的任意节点。解法:我偷了个懒,直接把这棵树看成一个无向图,用DFS来进行暴力搜索解决问题。因为没有什么数据顺序或是范围的限制,所以搜索剪枝好像也不太容易。代码: 1 // 4.9 Find all paths in a binary tree, the path doesn't have to start or end at the root or a leaf node. 2 #include 3 #include 4 #include ..
阅读全文
《Cracking the Coding Interview》——第4章:树和图——题目8
摘要:2014-03-19 05:04题目:给定两棵二叉树T1和T2,判断T2是否是T1的子树。子树的定义是,以T1的某个节点(可以是T1的根)作为根节点,得到的这棵树和T2一模一样。解法:首先可以根据节点个数省去一大部分不必要的搜索,然后再递归判断。代码还比较简单,请看下面。代码: 1 // 4.8 Check if a tree is a subtree of another. 2 #include 3 #include 4 using namespace std; 5 6 struct TreeNode { 7 int val; 8 TreeNode *l...
阅读全文
《Cracking the Coding Interview》——第4章:树和图——题目7
摘要:2014-03-19 04:48题目:最近公共父节点问题。解法1:Naive算法,先对其高度,然后一层一层往上直到找到结果。代码: 1 // 4.7 Least Common Ancestor 2 // This solution is Naive Algorithm, may timeout on very large and skewed trees. 3 #include 4 #include 5 using namespace std; 6 7 const int MAXN = 10005; 8 // tree[x][0]: parent of node x 9...
阅读全文
《Cracking the Coding Interview》——第4章:树和图——题目6
摘要:2014-03-19 04:16题目:找出一棵二叉搜索树中的中序遍历后继节点,每个节点都有指针指向其父节点。解法1:分两种情况:向下走时,先右后左;向上走时,先左后右。如果目标节点有右子树,就向右下走,否则往左上走。话说,如果没有父指针的话,还是一口气进行各中序遍历,求出所有结果比较有效率。代码: 1 // 4.6 Find the inorder successor of a node in the binary tree. 2 // online algorithm with parent pointer. 3 #include 4 #include 5 using name...
阅读全文
《Cracking the Coding Interview》——第4章:树和图——题目5
摘要:2014-03-19 04:11题目:设计算法检查一棵二叉树是否为二叉搜索树。解法:既然是二叉搜索树,也就是说左子树所有节点都小于根,右子树所有节点都大于根。如果你真的全都检查的话,那就做了很多重复工作。只需要将左边最靠右,和右边最靠左的节点和根进行比较,然后依照这个规则递归求解即可。代码: 1 // 4.5 Check if a binary tree is binary search tree. 2 #include 3 using namespace std; 4 5 struct TreeNode { 6 int val; 7 TreeNode *left; 8 ...
阅读全文
《Cracking the Coding Interview》——第4章:树和图——题目4
摘要:2014-03-19 03:40题目:给定一棵二叉树,把每一层的节点串成一个链表,最终返回一个链表数组。解法:前序遍历,遍历的同时向各个链表里添加节点。水平遍历好像还不如前序遍历来得方便。代码: 1 // 4.4 Level order traversal 2 #include 3 #include 4 using namespace std; 5 6 struct TreeNode { 7 int val; 8 TreeNode *left; 9 TreeNode *right; 10 11 TreeNode(int _val...
阅读全文
《Cracking the Coding Interview》——第4章:树和图——题目3
摘要:2014-03-19 03:34题目:给定一个排好序的数组,设计算法将其转换为一棵二叉搜索树,要求树的高度最小。解法:递归生成平衡二叉树,使左右子树的节点数尽量相等,所以对半开最好了。其实也可以生成一棵完全二叉树,不过写法应该不是很方便。代码: 1 // 4.3 Convert sorted unique array to height-balanced binary search tree. 2 #include 3 using namespace std; 4 5 struct TreeNode { 6 int val; 7 TreeNode *left; 8 ...
阅读全文
《Cracking the Coding Interview》——第4章:树和图——题目2
摘要:2014-03-19 03:32题目:给定一个有向图,判断其中两点是否联通。解法:DFS搜索解决,如果是无向图的话,就可以用并查集高效解决问题了。代码: 1 // 4.2 Write a program to check if there exists a path between two nodes in a directed graph. 2 #include 3 #include 4 #include 5 #include 6 #include 7 using namespace std; 8 9 struct GraphNode { 10 int...
阅读全文
《Cracking the Coding Interview》——第4章:树和图——题目1
摘要:2014-03-19 03:30题目:判断一个二叉树是否为平衡二叉树,即左右子树高度相差不超过1。解法:递归算高度并判断即可。代码: 1 // 4.1 Implement an algorithm to check if a bianry tree is height-balanced. 2 #include 3 #include 4 #include 5 using namespace std; 6 7 struct TreeNode { 8 int val; 9 TreeNode *left;10 TreeNode *right;11 12 ...
阅读全文
《Cracking the Coding Interview》——第3章:栈和队列——题目7
摘要:2014-03-19 03:20题目:实现一个包含阿猫阿狗的先入先出队列,我要猫就给我一只来的最早的猫,要狗就给我一只来的最早的狗,随便要就给我一只来的最早的宠物。建议用链表实现。解法:单链表可以实现一个简单的队列,这种有不同种类数据的队列,可以用if语句选择,也可以用一个堆做时间上的优化。对于来的时间,我用一个64位整数表示时间戳,在地球被太阳吃掉以前,这个数字是不大可能上溢的,所以问题应该不大。代码: 1 // 3.7 Implement a queue that holds cats and dogs. If you want dog or cat, you get the oldes.
阅读全文
《Cracking the Coding Interview》——第3章:栈和队列——题目6
摘要:2014-03-19 03:01题目:给定一个栈,设计一个算法,在只使用栈操作的情况下将其排序。你可以额外用一个栈。排序完成后,最大元素在栈顶。解法:我在草稿纸上试了试{1,4,2,3}之类的小例子,大概两三分钟有了思路。既然比较性排序是基于比较和交换的,那么就在两个栈的栈顶进行比较,同时在栈顶进行交换,此处需要O(1)的空间来进行交换。具体实现请看代码,时间复杂度为O(n^2)。代码: 1 // 3.6 Try to sort the elements in a stack with the aid of at most one more stack. 2 #include 3 #incl.
阅读全文
《Cracking the Coding Interview》——第3章:栈和队列——题目4
摘要:2014-03-18 05:28题目:你肯定听过汉诺威塔的故事:三个柱子和N个从小到大的盘子。既然每次你只能移动放在顶上的盘子,这不就是栈操作吗?所以,请用三个栈来模拟N级汉诺威塔的玩法。放心,N不会很大的。解法:递归着玩儿吧,还挺容易写的。要是迭代,我估计够呛。代码: 1 // 3.4 Implement Hanoi Tower with three stacks. 2 #include 3 #include 4 using namespace std; 5 6 class Solution { 7 public: 8 void initHanoiTower(i...
阅读全文
《Cracking the Coding Interview》——第3章:栈和队列——题目3
摘要:2014-03-18 05:17题目:设计一个栈,这个栈实际上由一列子栈组成。每当一个子栈的大小达到n,就新产生下一个子栈。整个栈群对外看起来就像普通栈一样,支持取顶top()、压入push()、弹出pop()操作。另外再实现一个弹出特定子栈popAt()的操作。解法:用stack构成的数组,可以实现快速的随机访问。用stack构成的链表实现,可以防止在中间的一些子栈进行pop操作造成的空隙,但顺序访问的效率要低一些。得根据执行这些操作的偏好和频率来定。代码: 1 // 3.3 Implement a stack with multiple sub-stacks. If one substac
阅读全文
《Cracking the Coding Interview》——第3章:栈和队列——题目2
摘要:2014-03-18 05:08题目:实现一个栈,除了能进行push和pop之外,还能在O(1)时间内返回栈中最小的元素。解法:用另一个“最小栈”存放最小的元素,每当有不小于当前最小值的元素进栈时,就代表最小值更新了(就算与当前最小值相等,也代表个数变了)。这时,同时要将最小值进栈。这个最小栈的栈顶就是最小的元素。出栈时,遇到数据栈的栈顶元素与最小栈相等时,要同时将最小栈出栈;否则只弹出数据栈即可。代码: 1 // 3.2 Design a modified stack that in addition to Push and Pop can also provide minimum elem
阅读全文
《Cracking the Coding Interview》——第3章:栈和队列——题目1
摘要:2014-03-18 03:19题目:用一个数组实现3个栈。解法: 首先我想过让三个栈动态决定长度。要么左右各一个向中间靠拢,要么三个穿插着,后来都觉得实现起来太复杂,而且思路总有各种功能缺陷,会导致额外的时间或空间复杂度。所以,还是三等分成固定大小吧。好写又好用。代码:// 3.1 Use an array to implement three stacks.// three fixed-length stacks#include #include #include using namespace std;template class ThreeStack {public: Thre...
阅读全文
LeetCode - Reverse Words in a String
摘要:Reverse Words in a String2014.3.18 03:09Given an input string, reverse the string word by word.For example,Given s = "the sky is blue",return "blue is sky the".click to show clarification.Clarification:What constitutes a word?A sequence of non-space characters constitutes a word.
阅读全文
《Cracking the Coding Interview》——第2章:链表——题目7
摘要:2014-03-18 02:57题目:检查链表是否是回文的,即是否中心对称。解法:我的做法是将链表从中间对半拆成两条,然后把后半条反转,再与前半条对比。对比完了再将后半条反转了拼回去。这样不涉及额外的空间,比反转整条链表然后比较要来的好。如果你反转了整条链表又不用额外空间,接下来跟谁比去呢?代码: 1 // 2.7 To Check the given linked list is palindrome or not? 2 #include 3 #include 4 using namespace std; 5 6 struct ListNode { 7 int v...
阅读全文
《Cracking the Coding Interview》——第2章:链表——题目6
摘要:2014-03-18 02:41题目:给定一个带有环的单链表,找出环的入口节点。解法1:用hash来检测重复节点肯定是容易想而且效率也高的好办法。代码: 1 // 2.6 You have a circular Linked List: a->b->c->d->e->c. Find where the cycle starts. 2 #include 3 #include 4 using namespace std; 5 6 struct ListNode { 7 int val; 8 ListNode *next; 9 ListNode(int x): val(
阅读全文
《Cracking the Coding Interview》——第2章:链表——题目5
摘要:2014-03-18 02:32题目:给定两个由单链表表示的数字,返回它们的和。比如(9->9) + (1->2) = 0->2->1,99 + 21 = 120。解法:逐位相加,注意处理进位、长度不等。代码: 1 // 2.5 Given two numbers represented by two lists, write a function that returns sum list. The sum list is list representation of addition of two input numbers. 2 // Example First
阅读全文
《Cracking the Coding Interview》——第2章:链表——题目4
摘要:2014-03-18 02:27题目:将一个单链表按照一个值X分为两部分,小于X的部分放在大于等于X的部分之前。解法:按照值和X的大小,分链表为两条链表,然后连起来成一条。代码: 1 // 2.4 Write code to partition a linked list around a value x, such that all nodes less than x comes before all nodes greater than or equal to x. 2 #include 3 using namespace std; 4 5 struct ListNode { 6 ...
阅读全文
《Cracking the Coding Interview》——第2章:链表——题目3
摘要:2014-03-18 02:25题目:给定一个单链表中间的节点,删掉那个节点。解法:把后面节点的数据域拷到当前节点来,然后删除后面那个节点。当前节点不是尾巴,所以后面不为空。代码: 1 // 2.2 Remove a node from middle of a linked list 2 #include 3 using namespace std; 4 5 struct ListNode { 6 int val; 7 struct ListNode *next; 8 ListNode(int x): val(x), next(nullptr) {}; 9 };10...
阅读全文
《Cracking the Coding Interview》——第2章:链表——题目2
摘要:2014-03-18 02:24题目:给定一个单链表,找出倒数第K个节点。解法:让一个指针先走K步,然后俩指针一起走到尽头。当然也可以先走到尽头数出链表的长度,然后第二次少走K步。其实耗费的工夫是一样的,但貌似总有人觉得第一种方法很巧妙很优美。代码: 1 // 2.2 Remove a node from middle of a linked list 2 #include 3 using namespace std; 4 5 struct ListNode { 6 int val; 7 struct ListNode *next; 8 ListNode(int x...
阅读全文
《Cracking the Coding Interview》——第2章:链表——题目1
摘要:2014-03-18 02:16题目:给定一个未排序的单链表,去除其中的重复元素。解法1:不花额外空间,使用O(n^2)的比较方法来找出重复元素。代码: 1 // 2.1 Remove duplicates from a linked list 2 // inefficient without hashing space 3 #include 4 #include 5 using namespace std; 6 7 struct ListNode { 8 int val; 9 struct ListNode *next;10 ListNode(int x): v...
阅读全文
《Cracking the Coding Interview》——第1章:数组和字符串——题目8
摘要:2014-03-18 02:12题目:判断一个字符串是否由另一个字符串循环移位而成。解法:首先长度必须相等。然后将第一个串连拼两次,判断第二个串是否在这个连接串中。代码: 1 // 1.8 Assume you have a method isSubstring which checks if one word is a substring of another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring (i.e.
阅读全文
《Cracking the Coding Interview》——第1章:数组和字符串——题目7
摘要:2014-03-18 01:55题目:给定一个MxN矩阵,如果某个元素为0,则将对应的整行和整列置为0。解法:单独挑出一行和一列作为标记数组。因为某元素为0就全部置为0,所以不论A[i][j]为0中的j是几,第i行总会被置为0的。再用O(1)的额外空间去标记单独挑出的那一行一列是否包含0即可。要注意最后清零的顺序和范围不要错了。代码: 1 // 1.7 Write an algorithm such that if an element in an MxN matrx is 0, its antire row and column are set to 0. 2 #include 3 ...
阅读全文
《Cracking the Coding Interview》——第3章:栈和队列——题目5
摘要:2014-03-18 05:33题目:用两个栈来实现一个队列。解法:栈是反的,队列是正的,反了再反就正过来了。所以,请看代码。操作中时间复杂度有O(1)的,有O(n)的,但均摊下来时间符合O(1)。代码: 1 // 3.5 Implement a queue MyQueue using two stacks. 2 #include 3 #include 4 #include 5 #include 6 using namespace std; 7 8 template 9 class MyQueue {10 public:11 bool empty() {12 ...
阅读全文
《Cracking the Coding Interview》——第1章:数组和字符串——题目6
摘要:2014-03-18 01:45题目:给定一个NxN的矩阵,就地旋转90度。(没有样例又不说方向的话,随便往哪儿转。)解法:如果N为奇数,除了中心点以外四等分。如果N为偶数,四等分。按照A->B->C->D->A的方式,轮换赋值,需要O(1)的额外空间保存A的值。代码: 1 // 1.6 Given an image represented by an NXN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can yo
阅读全文
《Cracking the Coding Interview》——第1章:数组和字符串——题目5
摘要:2014-03-18 01:40题目:对字符串进行类似游程编码的压缩,如果压缩完了长度更长,则返回不压缩的结果。比如:aabcccccaaa->a2b1c5a3,abc->abc。解法:Count and say.代码: 1 // 1.5 Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2b1c5a3. If the compressed s
阅读全文
《Cracking the Coding Interview》——第1章:数组和字符串——题目4
摘要:2014-03-18 01:36题目:给定一个字符串,将其中的空格‘ ’替换为‘%20’,你可以认为字符串尾部有足够空间来容纳新增字符。请不要额外开辟数组完成。解法:先从前往后统计空格个数,然后从后往前填充字符,以免其他无关字符被‘%20’覆盖掉。代码: 1 // 1.4 Write a method to replace all spaces in a string with '%20'. 2 // do it in-place and backward. 3 #include 4 #include 5 using namespace std; 6 7 class Solut
阅读全文
《Cracking the Coding Interview》——第1章:数组和字符串——题目3
摘要:2014-03-18 01:32题目:对于两个字符串,判断它们是否是Anagrams。解法:统计俩单词字母构成是否相同即可。代码: 1 // 1.3 Given two strings, write a method to decide if one is a permutation of the other. 2 // count them. 3 #include 4 #include 5 using namespace std; 6 7 class Solution { 8 public: 9 bool isPermutation(const char *s, const c...
阅读全文
《Cracking the Coding Interview》——第1章:数组和字符串——题目2
摘要:2014-03-18 01:30题目:反转一个char *型的C/C++字符串。解法:一头一尾俩iterator,向中间靠拢并且交换字符。代码: 1 // 1.2 Implement a function void reverse(char *str) in C or C++ which reverses a null-terminated string. 2 #include 3 #include 4 using namespace std; 5 6 void reverse(char *str) 7 { 8 if (nullptr == str) { 9 re...
阅读全文
《Cracking the Coding Interview》——第1章:数组和字符串——题目1
摘要:2014-03-18 01:25题目:给定一个字符串,判断其中是否有重复字母。解法:对于可能有n种字符的字符集,用一个长度为n的数组统计每个字符的出现次数,大于1则表示有重复。代码: 1 // 1.1 Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structure? 2 #include 3 #include 4 using namespace std; 5 6 class Solution { 7 pub...
阅读全文
LeetCode - Regular Expression Matching
摘要:Regular Expression Matching2014.3.1 20:55Implement regular expression matching with support for'.'and'*'.'.' Matches any single character.'*' Matches zero or more of the preceding element.The matching should cover the entire input string (not partial).The function pro
阅读全文