Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

How to create a data structure that supports insert, remove, print and get random element in Java

1 Answer

0 votes
import java.util.List;
import java.util.Random;
import java.util.Arrays;
import java.util.HashMap;
import java.util.ArrayList;

public class Program
{
    HashMap<Integer, Integer> hm;
    List<Integer> list;
        
    public Program() {
        hm = new HashMap<>();
        list = new ArrayList<>();
    }
        
    public boolean insert(int val) {
        if (hm.containsKey(val)) 
            return false;
        
        list.add(val);
        hm.put(val, list.size() - 1);
        
        return true;
    }
        
    public boolean remove(int val) {
        if (hm.containsKey(val)) {
            int last = list.get(list.size() - 1);
            
            hm.put(last,hm.get(val));
            list.set(hm.get(val), last);
            list.remove(list.size() - 1);
            hm.remove(val);
            
            return true;
        }
        return false;
    }
        
    public static int generateRandomInteger(int min, int max) {
        return new Random().nextInt(max - min + 1) + min;
    }
    
    public int getRandom() {
        int rnd = (int)(generateRandomInteger(0, list.size()));
        
        return list.get(rnd);
    }
    
    public void print() {
        System.out.println(Arrays.toString(list.toArray()));
    }
    
    public static void main(String[] args) {
        Program obj = new Program();

        obj.insert(6);
        obj.insert(9);
        obj.insert(8);
        obj.insert(2);
        obj.insert(1);
        
        System.out.println(obj.getRandom());
        
        obj.remove(2);
     
        obj.print();
  }
}



/*
run:

9
[6, 9, 8, 1]

*/

 



answered Jan 29, 2024 by avibootz

Related questions

...