18.6 Describe an algorithm to find the smallest one million numbers in one billion numbers. Assume that the computer memory can hold all one billion numbers. 这道题让我们在十亿个数字中找到最小的一百万个数字,而且限定了计算机只有能存十亿个数字的内存.这题有三种解法,排序,最小堆,和选择排序. 首先来看排序方法,这种方法简单明了,就是把这十亿…
18.1 Write a function that adds two numbers. You should not use + or any arithmetic operators. 这道题让我们实现两数相加,但是不能用加号或者其他什么数学运算符号,那么我们只能回归计算机运算的本质,位操作Bit Manipulation,我们在做加法运算的时候,每位相加之后可能会有进位Carry产生,然后在下一位计算时需要加上进位一起运算,那么我们能不能将两部分拆开呢,我们来看一个例子759+674 1.…
18.9 Numbers are randomly generated and passed to a method. Write a program to find and maintain the median value as new values are generated. LeetCode上的原题,请参见我之前的博客Find Median from Data Stream. 解法一: priority_queue<int> small; priority_queue<int,…
You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k. Define a pair (u,v) which consists of one element from the first array and one element from the second array. Find the k pairs (u1,v1),(u2,v2) ...(uk,vk) wit…
18.12 Given an NxN matrix of positive and negative integers, write code to find the submatrix with the largest possible sum. 这道求和最大的子矩阵,跟LeetCode上的Maximum Size Subarray Sum Equals k和Maximum Subarray很类似.这道题不建议使用brute force的方法,因为实在是不高效,我们需要借鉴上面LeetCode…
18.11 Imagine you have a square matrix, where each cell (pixel) is either black or white. Design an algorithm to find the maximum subsquare such that all four borders are filled with black pixels. LeetCode上的原题,请参见我之前的解法Maximal Square.书上给了两种解法,但是比较长:…
18.10 Given two words of equal length that are in a dictionary, write a method to transform one word into another word by changing only one letter at a time. The new word you get in each step must be in the dictionary. 这道题让我们将一个单词转换成另一个单词,每次只能改变一个字母,…
18.8 Given a string s and an array of smaller strings T, design a method to search s for each small string in T. 这道题给我们一个字符串s,和一个字符串数组T,让我们找T中的每一个小字符串在s中出现的位置,这道题很适合用后缀树Suffix Tree来做,LeetCode中有几道关于前缀树(Prefix Tree, Trie)的题,Implement Trie (Prefix Tree)…
18.5 You have a large text file containing words. Given any two words, find the shortest distance (in terms of number of words) between them in the file. If the operation will be repeated many times for the same file (but different pairs of words), c…
18.4 Write a method to count the number of 2s between 0 and n. 这道题给了我们一个整数n,让我们求[0,n]区间内所有2出现的个数,比如如果n=20,那么满足题意的是2, 12, 20,那么返回3即可.LeetCode上有一道很类似的题Factorial Trailing Zeroes,但是那道题求5的个数还包括了因子中的5,比如10里面也有5,这是两题的不同之处.那么首先这题可以用brute force来解,我们对区间内的每一个数字…