-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomizedSet.java
More file actions
89 lines (77 loc) · 2.31 KB
/
RandomizedSet.java
File metadata and controls
89 lines (77 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
public class RandomizedSet
{
Map<Integer, Integer> _set;
List<Integer> _list;
int _index;
Random _random;
/** Initialize your data structure here. */
public RandomizedSet()
{
_set = new HashMap<>();
_list = new ArrayList<>();
_index = 0;
_random = new Random();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert( int val )
{
if ( _set.containsKey( val ) )
return false;
_list.add( val );
_set.put( val, _index++ );
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove( int val )
{
if ( !_set.containsKey( val ) )
return false;
int pos = _set.get( val );
if ( pos != _index )
{
_list.set( pos, _list.get( _index - 1 ) );
_set.put( _list.get( pos ), pos );
}
_list.remove( _index - 1 );
_index--;
_set.remove( val );
return true;
}
/** Get a random element from the set. */
public int getRandom()
{
// System.out.println( Arrays.toString( _list.toArray( new Integer[0] ) ) );
int n = _random.nextInt( _index );
return _list.get( n );
}
public static void main( String[] args )
{
RandomizedSet r = new RandomizedSet();
String[] action = { "insert", "insert", "remove", "insert", "insert", "insert", "remove", "remove", "insert", "remove",
"insert", "insert", "insert", "insert", "insert", "getRandom", "insert", "remove", "insert", "insert" };
int[] vals = { 3, -2, 2, 1, -3, -2, -2, 3, -1, -3, 1, -2, -2, -2, 1, 0, -2, 0, -3, 1 };
for ( int i = 0; i < action.length; i++ )
run( r, action[i], vals[i] );
}
static void run( RandomizedSet r, String action, int val )
{
if ( action.equals( "insert" ) )
System.out.println( "insert\t" + val + " " + r.insert( val ) );
if ( action.equals( "remove" ) )
System.out.println( "remove\t " + val + " " + r.remove( val ) );
if ( action.equals( "getRandom" ) )
System.out.println( r.getRandom() );
}
}
/**
* 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();
*/