-
Question: 3-SUM in quadratic time. Design an algorithm for the 3-SUM problem that takes time proportional to n^2 in the worst case. You may assume that you can sort the n integers in time proportional to n^2 or better.
问题描述: 这里的问题是想要一个增长数量级是平方级别或更好的3-sum算法
解决方案: 增加一个哈希表来实现,先使用嵌套的2层循环,然后在哈希表中查询-(a[i] + a[j]), 当然要在数据结构里面加入flag数组来表示每个数是否作为嵌套循环里面的基底使用过了,如果哈希表中寻找到这个值且flag为false,那么count加1。
-
Question: Search in a bitonic array. An array is bitonic if it is comprised of an increasing sequence of integers followed immediately by a decreasing sequence of integers. Write a program that, given a bitonic array of n distinct integer values, determines whether a given integer is in the array.
- Standard version: Use ∼3lgn compares in the worst case.
- Signing bonus: Use ∼2lgn compares in the worst case (and prove that no algorithm can guarantee to perform fewer than ∼2lgn compares in the worst case).
问题描述: 这是关于双调数组搜索的问题,所谓的双调数组的特点是,数组元素先递增,再递减,类似于一个峰的形式。然后标准实现方法的最坏情况是~3lgn的比较次数,然后最好的实现方法的最坏情况比较次数是关于~2lgn的。
解决方案: 这里的标准解决方法很好实现,先使用二分法的变式找到数组的最大值,然后左右分别进行二分查找即可,很容易得到~3lgn的比较次数。对于更有效率的查找方式,这里我选择不查找最大值。具体的d递归实现方式描述如下:
- 先找到mid,将其与key比较,如果相等则返回true,否则进行下一步;
- 将mid值和左右两个值进行比较,判断mid在山峰的左边还是右边亦或是峰顶;
- 如果是峰顶,直接采取左右两边二分查找;如果是峰左,那么判定key值与mid值的相对大小,如果key值大于mid值,那么可以知道key值位于mid的右边,直接递归bitonicSearch(mid+1, hi, key)即可;如果key值小于mid值,那么需要对左边进行二分查找以及对右边进行递归查找;对于mid位于峰右的情况是同理的
- 3.Question: Egg drop. Suppose that you have an n-story building (with floors 1 through n) and plenty of eggs. An egg breaks if it is dropped from floor T or higher and does not break otherwise. Your goal is to devise a strategy to determine the value of T given the following limitations on the number of eggs and tosses:
Version 0: 1 egg, ≤T tosses.
Version 1: ∼1lgn eggs and ∼1lgn tosses.
Version 2: ∼lgT eggs and ∼2lgT tosses.
Version 3: 2 eggs and ∼2√n tosses.
Version 4: 2 eggs and ≤c√T tosses for some fixed constant c.
分析:
version0 : 拿着一个鸡蛋从1~n依次扔就可以,到floor T会碎,故复杂度为≤T
version 1: 采用二分查找,首先从n/2层开始扔:
if(鸡蛋碎) 从(n/2)/2层开始扔;
else 从n/2+(n/2)/2层开始扔
二分方法需要lgn个鸡蛋尝试lgn次
version 2: 依次从1, 2, 4, 8, 16, 32,...2k开始扔,如果鸡蛋在2k碎了,那么2k-1≤T≤2k,这时已经使用了 lgT 次步,接下来在[2k-1+1,2k)区间进行version1的二分查找方法,需要花费lgT步。这两种操作加起来总共花费2lgT步
version 3: 将0~n层楼分成[1, -1], [ , 2 -1], [2 ,3 -1]...[k , (k+1) -1]..个区间,用一个鸡蛋分布从1开始在各个区间的起始楼层扔,如果在k 层碎了,那就从(k-1) +1开始逐层扔。第一步区间选择用了 的复杂度,第二步区间内部扔鸡蛋用了 的复杂度,总共用了 2
version 4: 尝试从1, 4, 9, 16, 25,...(k-1)2, k2....楼层扔鸡蛋,加入鸡蛋在楼层k2碎了,意味着(k-1)2≤T≤k2,这一步尝试了 次(k= )。接着从楼层(k-1)2+1开始逐层扔,最多尝试至k2-1结束,这一步需要尝试k2-1-(k-1)2-1=2 -1=2 -2次。总共用了3 -2次