`

Data structure: insert, remove, contains, get random element, all at O(1)

 
阅读更多

From:

http://stackoverflow.com/questions/5682218/data-structure-insert-remove-contains-get-random-element-all-at-o1

Design a data structure that offers the following operations in O(1) time:

  • insert
  • remove
  • contains
  • get random element

Solution:

Consider a data structure composed of a hashtable H and an array A. The hashtable keys are the elements in the data structure, and the values are their positions in the array.

  1. insert(value): append the value to array and let i be it's index in A. Set H[value]=i.
  2. remove(value): We are going to replace the cell that contains value in A with the last element in A. let d be the last element in the array A at index m. let i be H[value], the index in the array of the value to be removed. Set A[i]=d, H[d]=i, decrease the size of the array by one, and remove value from H.
  3. contains(value): return H.contains(value)
  4. getRandomElement(): let r=random(current size of A). return A[r].

since the array needs to auto-increase in size, it's going to be amortize O(1) to add an element, but I guess that's OK.

public class ConstantRandomGet<E> {

	private Map<E, Integer> map = new HashMap<>();
	private List<E> list = new ArrayList<>();
	private Random random = new Random();
	
	public void insert(E e) {
		map.put(e, list.size());
		list.add(e);
	}
	
	public boolean remove(E e) {
		if(!map.containsKey(e)) return false;
		int i = map.get(e);
		int last = list.size()-1;
		E lastE = list.remove(last);
		map.put(lastE, i);
		list.set(i, lastE);
		return true;
	}
	
	public boolean contains(E e) {
		return map.containsKey(e);
	}
	
	public E getRandomElement() {
		int size = list.size();
		if(size == 0) return null;
		int index = random.nextInt(size);
		return list.get(index);
	}
}

 

分享到:
评论

相关推荐

    R for Data Science: Import, Tidy, Transform, Visualize, and Model Data

    With this book, you’ll gain a clear understanding of this discipline for discovering natural laws in the structure of data. Along the way, you’ll learn how to use the versatile R programming ...

    YOLOV4之dataloader的get_random_data模块的详细推导过程

    `get_random_data`是`dataloader`中的一个关键模块,用于对图像进行随机变换,增强数据集,从而提高模型的泛化能力。现在,我们将深入探讨`get_random_data`模块的详细推导过程及其各个参数的作用。 首先,`get_...

    利用getdata获取图形数据

    "利用getdata获取图形数据"这一主题涉及到一个名为getdata的软件工具,它专门用于从各种图形文件中提取数据点,使用户能够对这些数据进行进一步处理或分析。下面将详细介绍getdata软件及其使用方法。 getdata是一款...

    Swift Data Structure and Algorithms [2016]

    Swift Data Structure and Algorithms by Erik Azar English | 18 Nov. 2016 | ISBN: 1785884506 | 286 Pages | AZW3/MOBI/EPUB/PDF (conv) | 22.7 MB Master the most common algorithms and data structures, and...

    [PDF] Fundamentals of Data Structure in C

    Data structure + Algorithm = Programming The tools and techniques to design and implement large-scale computer systems: Data abstraction Algorithm specification Performance analysis Performance ...

    Smart Grid using Big Data Analytics A Random Matrix Theory Approach

    Smart Grid using Big Data Analytics:A Random Matrix Theory Approach 大数据与智能电网理论与实践 big data and smart grid theory and practice

    GetData Graph Digitizer

    此软件由俄国人开发(好多这种功能强大的小软件都是俄国人开发的,pfpf)getdata-graph-digitizer.com上可以下载到试用版,21天的试用期,好像无功能限制,目前最新版本:2.24,有中文和英文界面可供选择,其他有...

    科研论文图片数据提取工具:GetData2.20

    "科研论文图片数据提取工具:GetData2.20" 是一款专为科研工作者设计的实用软件,它能够帮助用户从科研论文中的图像中提取出所需的数据。在科研过程中,经常遇到的情况是,论文中的图表虽然直观展示了许多关键数据,...

    GetData 教程软件

    GetData Graph Digitizer是一款强大的图形化坐标读取工具,专门用于从数据曲线和散点图中精确提取原始数据点。这款软件对于科学家、工程师以及任何需要从图表中获取精确数值的人来说非常有用。它允许用户轻松地从...

    GetData安装包

    GetData是一款强大的数据提取工具,主要用于从图形图像中准确地获取曲线和点的数据。这款软件的安装包名为"GetData.Graph.Digitizer.v2.24.rar.zip",这表明我们正在处理的是GetData Graph Digitizer的v2.24版本,一...

    Data Structure Summary PDF 2pages include core elements

    Data Structure Summary: Time Complexity & Space ...O(1) O(n) O(log(n)) o(n log(n))... Data Structures Performance Sorting Algorithms Performance Graph Operations Performance Heap Operations Performance

    DATA MINING Concepts and Techniques 3rd(数据挖掘:概念与技术)

    The increasing volume of data in modern business and science calls for more complex ... *Provides a comprehensive, practical look at the concepts and techniques you need to get the most out of your data

    GetData2.26

    这款软件可以从图片上提取出曲线上的数据,可以自动提取,也可以对提取出的数据手动更改

    Here I've all the codes related to Data Structure and Algorithms

    Here I've all the codes related to Data Structure and Algorithms in python language.

    data-structure:javaScript实现的一些数据结构

    npm install -- save common - data - structure 例子 const { Stack } = require ( 'common-data-structure' ) const stack = new Stack ( ) // create an instance stack . push ( 5 ) // add an element stack . ...

    Fundamentals of Data Structure in C

    1. **数组**:数据结构的基础,是存储相同类型元素的连续内存空间。数组分为一维数组、二维数组和多维数组,它们在C语言中广泛用于简单的数据存储和处理。 2. **链表**:不同于数组,链表中的元素并不需要存储在...

    leetcodepushfront-Easy-Javascript-Data-Structure:简单的Javascript数据结构,学习笔记

    O(1) addFirst O(n) remove O(n) removeLast O(1) removeFirst O(n) removeElment O(n) find, contains, O(n) get, set O(1) 动态数组的扩容和缩容 不使用均摊复杂度分析,扩容的复杂度在 边界值 size 时, 复杂度为...

Global site tag (gtag.js) - Google Analytics