【问题标题】:A algorithm to track the status of a number一种跟踪号码状态的算法
【发布时间】:2020-03-14 16:10:06
【问题描述】:

要设计一个 API,

  1. get(),它会返回随机数,而且数字不能重复,意味着它永远是唯一的。
  2. put(randomvalue),它会将get()生成的随机数放回去,如果放回去,get()函数可以重用这个数字作为输出。

它必须是高效的,没有过多的资源被高度使用。

有没有办法实现这个算法?不推荐使用 hashmap,因为如果这个 API 为数十亿的请求生成,保存生成的随机数仍然占用太多空间。

我无法计算出这个算法,请帮忙提供线索,提前谢谢!

【问题讨论】:

  • 您使用哪种语言以及您的努力是什么?
  • 如果不使用map或者set,如何保证一个数字不生成两次?
  • 您可以尝试将已经选择的随机数存储在 TreeSet 中(来自 javadoc:This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).)。所以它比HashMap 更节省时间,也更节省空间。
  • 这是一个考试问题,还是类似的问题?出于实际目的,我认为您没有理由需要 put() 函数。只需忽略已经过时的数字。
  • 使用linear congruential generator,句点为 2^64。即使每秒有 10 亿个 get() 请求,也需要 500 多年才能重复一个数字。 put() 请求是 no-op,忽略它。您“可以重复使用此号码” 的声明并不意味着您“必须重复使用此号码”

标签: algorithm system-design


【解决方案1】:

如果没有额外的空间,我想不出任何解决方案。有了空格,一个选项可以是使用 TreeMap,首先将 treeMap 中的所有元素添加为 false。当元素被访问时,标记为真。与 put 类似,将值更改为 false。 下面的代码sn-p...

public class RandomNumber {

public static final int SIZE = 100000;
public static Random rand;
public static TreeMap<Integer, Boolean> treeMap;

public RandomNumber() {
    rand = new Random();
    treeMap = new TreeMap<>();
}

static public int getRandom() {
    while (true) {
        int random = rand.nextInt(SIZE);
        if (!treeMap.get(random)) {
            treeMap.put(random, true);
            return random;
        }
    }
}

static public void putRandom(int number) {
    treeMap.put(number, false);
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-16
    • 2011-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多