Coursera - Algorithm (Princeton) - 习题与解答 - Week 4

本篇博客主要介绍了Coursera算法课程第四周的内容,包括如何设计一个支持动态中位数查找的数据结构,实现随机优先队列,探讨Taxicab Numbers的算法以及讨论Java自动装箱与equals()方法的特殊情况。此外,还讲解了检查二叉树是否为BST以及仅使用常数额外空间的中序遍历方法。
摘要由CSDN通过智能技术生成

Week 4

Dynamic Median

题目

Design a data type that supports insert in logarithmic time, find-the-median in constant time, and remove-the-median in logarithmic time. If the number of keys in the data type is even, find/remove the lower median.

分析(非原创)

基本看来就是用堆来实现一个寻找中位数的数据结构(数组能够做到常数时间定位中位数,但是排序最优是对数线性的),但是单纯一个堆是无法做到的,在网上查到使用一个最大堆和一个最小堆进行维护

设计

思路参考:https://blog.csdn.net/pngynghay/article/details/22209387

  1. 创建两个堆(一个小根堆、一个大根堆),堆大小至少为给定数据个数的一半,(size+1)/2,即向上取整;
  2. 假定变量mid用来保存中位数,取定第一个元素,赋值给mid,即作为初始的中位数;
  3. 依次遍历后面的每一个数据,如果比mid小,则插入大根堆;否则插入小根堆;
  4. 如果大根堆和小根堆上的数据个数相差为2,则将mid插入到元素个数较少的堆中,然后从元素个数较多的堆中删除根节点,并将跟节点赋值给mid;
  5. 重复步骤3和4,直到所有的数据遍历结束;

此时,mid保存了一个数,再加上两个堆中保存的数,就构成了给定数据的集合。

如果两个堆中元素个数相等,则mid即为最终的中位数;否则,元素较多的堆的根节点元素与mid的和求平均值,即为最终的中位数。

Randomized Priority Queue

题目

Describe how to add the methods s a m p l e ( ) \mathtt{sample()} sample() and d e l R a n d o m ( ) \mathtt{delRandom()} delRandom() to our binary heap implementation. The two methods return a key that is chosen uniformly at random among the remaining keys, with the latter method also removing that key. The s a m p l e ( ) \mathtt{sample()} sample() method should take constant time; the d e l R a n d o m ( ) \mathtt{delRandom()} delRandom() method should take logarithmic time. Do not worry about resizing the underlying array.

分析

就是在数组实现的堆上进行均匀随机采样的实现

设计

前一个方法就是直接在数组上均匀随机选择一个可好,后一个方法在选择之后,就执行和移去最大值一样的方法,将对应元素与最后一个元素调换,然后执行sink方法回复堆有序

Taxicab Numbers

题目

A taxicab number is an integer that can be expressed as the sum of two cubes of positive integers in two different ways: a 3 + b 3 = c 3 + d 3 a^3 + b^3 = c^3 + d^3 a3+b

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值