Interview - mergesort

  1. Merging with smaller auxiliary array. Suppose that the subarray a[0] to a[n−1] is sorted and the subarray a[n] to a[2∗n−1] is sorted. How can you merge the two subarrays so that a[0] to a[2∗n−1] is sorted using an auxiliary array of length n (instead of 2n)?
    描述: 使用n而不是2n的额外存储空间来对数列的两个子数列进行归并。
    解答: 设辅助数组为aux[], 将a[]的前半个子数列拷贝到aux[],然后根据aux[i](i从0开始)和a[j](j从n开始)的大小关系往a[k](k从0开始)里面放置相应元素。

  2. Counting inversions. An inversion in an array a[] is a pair of entries a[i] and a[j] such that i < j but a[i]>a[j]. Given an array, design a linearithmic algorithm to count the number of inversions.
    描述: 计算数列中的逆序对的个数,要求算法的复杂度是线性对数的。
    解答: 事实上数列里面逆序对的个数就等于排序里面需要执行交换操作的次数。使用递归的思想,先求出左边子数列的逆序数,再求出右边子数列的逆序数,加上左右两边因为分开元素产生的逆序数,就得到了总的逆序数。主要是针对归并排序作修改,在merge方法里面加入逆序数count的操作,count += 此轮判定的逆序数。

  3. Shuffling a linked list. Given a singly-linked list containing n items, rearrange the items uniformly at random. Your algorithm should consume a logarithmic (or constant) amount of extra memory and run in time proportional to nlogn in the worst case.
    描述: 对一个链表进行随机化操作。
    解答: 看stackoverflow吧,这个我也比较迷糊。stackoverflow

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值