CS106B Section Solutions #5

这个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比较最长子串,最后留下来的就是最长子串。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值