Interview-quicksort

Nuts and bolts. A disorganized carpenter has a mixed pile of n nuts and n bolts. The goal is to find the corresponding pairs of nuts and bolts. Each nut fits exactly one bolt and each bolt fits exactly one nut. By fitting a nut and a bolt together, the carpenter can see which one is bigger (but the carpenter cannot compare two nuts or two bolts directly). Design an algorithm for the problem that uses nlogn compares (probabilistically).
描述: 一个混乱的木匠有n个螺母和n个螺栓的混合堆。 目标是找到相应的螺母和螺栓对。 每个螺母恰好适合一个螺栓,每个螺栓恰好适合一个螺母。 通过将螺母和螺栓装配在一起,木匠可以看到哪一个更大(但是木匠不能直接比较两个螺母或两个螺栓)。 设计一个使用nlogn比较的问题的算法(概率)。。
解答:

  • 这里不能直接比较螺母或者螺栓,所以转换一下思路,将螺母螺丝当成彼此的pivot,分别分成两堆。
  • 先选取一个螺母,将螺丝分成两堆,其中有一个相符合的螺丝
  • 将这个螺丝作为pivot,将螺母分成两堆
  • 这样螺母螺丝已经被分成两堆,再递归进行这样的分组即可


Selection in two sorted arrays. Given two sorted arrays a[] and b[], of sizes n1 and n2, respectively, design an algorithm to find the kth largest key. The order of growth of the worst case running time of your algorithm should be logn, where n=n1+n2.

  • Version 1: n1=n2 and k=n/2
  • Version 2: k=n/2
  • Version 3: no restrictions

描述: 有两个有序数组,设计算法找到第k大的值。
解答: 这里用到的是k值不变的特性,分别在数组a和b中截取的那部分加起来一共是k个元素。假设数组长度都大于k,如果a截取的中间值大于b截取的中间值,那么a的后半部分就可以忽略了,相反同理,每次循环里面步长减半。下面是python实现代码:

    def f(a, b, k):
        i = k/2
        j = k - i
        step = k/4
        while step > 0:
            if a[i-1] > b[j-1]:
                i -= step
                j += step
            else
                i += step
                j -= step
            step /= 2

        if a[i-1] > b[j-1]:
            return a[i-1]
        else
            return b[j-1]

Decimal dominants. Given an array with n keys, design an algorithm to find all values that occur more than n/10 times. The expected running time of your algorithm should be linear.
描述: 小数统计。 给定一个具有n个键的数组,设计一个线性的算法来查找超过n / 10次的所有值。
解答: 直接用hashmap来做很简单啊。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值