您的位置:首页 > 健康 > 美食 > 制作网站免费建站_千锋教育学费一览表_如何优化网络_国外网站谷歌seo推广

制作网站免费建站_千锋教育学费一览表_如何优化网络_国外网站谷歌seo推广

2025/5/6 11:48:55 来源:https://blog.csdn.net/weixin_74175349/article/details/147071336  浏览:    关键词:制作网站免费建站_千锋教育学费一览表_如何优化网络_国外网站谷歌seo推广
制作网站免费建站_千锋教育学费一览表_如何优化网络_国外网站谷歌seo推广

为了保证常数时间插入和获取采用可变数组存储数据,那么在删除一个随机元素时如果需要移动元素需要n时间复杂度,那么进一步优化可以采用哈希表获取删除元素所在的位置然后把最后一个元素覆盖到要删除的位置最后再把最后一个元素删除掉,这样就可以避免循环移动覆盖的时间开销

class RandomizedSet {private List<Integer> nums;private Map<Integer,Integer> indicies;private Random random;public RandomizedSet() {nums = new ArrayList<>();indicies = new HashMap<>();random = new Random();}public boolean insert(int val) {if (indicies.containsKey(val)) {return false;} else {int index = nums.size();nums.add(val);indicies.put(val, index);return true;}}public boolean remove(int val) {if (!indicies.containsKey(val)) {return false;} else {//将最后一个元素覆盖到要删除的元素,再删除最后一个元素Integer index = indicies.get(val);Integer lastValue = nums.get(nums.size() - 1);nums.set(index, lastValue);nums.remove(nums.size() - 1);indicies.put(lastValue, index);indicies.remove(val);return true;}}public int getRandom() {return nums.get(random.nextInt(nums.size()));}
}/*** Your RandomizedSet object will be instantiated and called as such:* RandomizedSet obj = new RandomizedSet();* boolean param_1 = obj.insert(val);* boolean param_2 = obj.remove(val);* int param_3 = obj.getRandom();*/

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com