<编程珠玑>笔记 三个算法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了<编程珠玑>笔记 三个算法相关的知识,希望对你有一定的参考价值。

 在第二章里,作者提出了三个问题,然后慢慢引出对应的算法实现。

1  Binary search 二分查找

  Given a sequential file that contain at most 4x109 32-bit integers in random order, find a 32-bit integer that is not in the file.

  How would you solve this problem with ample main memory?

  How would you solve it if you could use several external "scratch" files but only a few hundred bytes of main memory? 

1)  bitmap technique

  With ample main memory, we could use the bitmap technique and dedicate 232 8-bit bytes to a bitmap representing the integers.

2)  binary search

   技术分享      技术分享 

  The insight is that we can probe a range by counting the elements above and below its midpoint: either the upper or the lower range has at most half the elements in the total range. Because the total range has a missing element, the smaller half must also have a missing element.

  Its only drawback is that the entire table must be known and sorted in advance.

 

2  Rotate -> reverse

  Rotate a one-dimensional vector x of n elements left by i positions. For instance, with n=8 and i=3, the vector abcdefgh is rotated into defghabc.

  Can you rotate the vector in time proportional to n using only a few dozen extra bytes of storage?

1) time and space constraints

  space-expensive -- copy the first i elementsto a temporary array, move the remaining (n-i) elements left i places, and then copy the first i from the temporary array back to the last position in x.

  time-expensive -- define a function to rotate x left one position(in time proportional to n) and call it times.

2) delicate juggling act

  move x[0] to the temporary t, then move x[i] to x[0], x[2i] to x[i], and so on, until we come back to taking an element from x[0], at which point we instead take the element from t and stop the process.

  When i is 3 and n is 12, that phase moves the elements in this order. If that process did not move all the elements, then we start over at x[1], and continue until we move all the elements.

  技术分享

3) revese

  starting with ab, we reverse a to get arb, reverse b to get arbr, and then reverse the whole thing to get (arbr)r, which is exactly ba

reverse(0, i-1)    // cbadefgh
reverse(i, n-1)    // cbahgfed
reverse(0, n-1)    // defghabc

 

3  Signatures

  Given a dictionary of English words, find all sets of anagram.

  For instance, "pots", "stop" and "tops" are all anagrams of each other.

技术分享

 

以上是关于<编程珠玑>笔记 三个算法的主要内容,如果未能解决你的问题,请参考以下文章

<编程珠玑>笔记 四条原则

<编程珠玑>笔记 程序验证

编程珠玑第一章中的代码

[读书笔记·编程珠玑] 数组移位(待填坑)

编程珠玑第一章习题

第8周读书笔记-读《编程珠玑》有感