这个section的练习都是有关时间复杂度的问题,咱们快速过一遍,最后一个算法题还是很有意思的
Problem 1: Big-O
a) o(n^2)
b) o(1)
c) o(log2(n))
d) o(2^n)
Problem 2: Searching and Sorting
公式为: cost of sort + (x * cost of binary search) < x * cost of linear search
选择排序具有O(n^2)的运行时间,而合并排序具有O(n log n)的运行时间
Problem 3: Those Big-O Constant Factors
简单说就是比如选择排序时间更多,归并排序时间短,但是归并排序数据结更复杂,所以o()前设定的常数要更大。
Problem 4: Search Algorithms
pass
Problem 5: Algorithmic Problem Solving
寻找连续最大的子串,直接给出最简单的写法,可以达到o(n)的时间复杂度
int find(Vector<int> v), int n)
{
int i,maxsofar,maxendinghere;
maxsofar = 0;
maxendinghere = 0;
for(i=0; i<n; i++){
maxendinghere = max(maxendinghere + v[i], 0);
maxsofar = max(maxsofar, maxendinghere);
}
return maxsofar;
}
maxendinghere是最长子串结束的意思,和0比较是因为如果大于0则该从这里继续仍然可能是最长子串,如果小于0则不可能,用maxsofar比较最长子串,最后留下来的就是最长子串。