-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
29 lines (24 loc) · 767 Bytes
/
Solution.java
File metadata and controls
29 lines (24 loc) · 767 Bytes
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
class MedianFinder {
ArrayList al; // field var to hold the current sorted arraylist of integers
public MedianFinder()
{
al = new ArrayList();
}
public void addNum(int num)
{
al.add(num);
}
public double findMedian()
{
al.sort(Comparator.naturalOrder()); //By ordering the arraylist when finding median we save time
// check if even
if(al.size()%2 == 0)
{
return((double)((int)(al.get(al.size()/2 -1))+(int)(al.get(al.size()/2)))/2); // returns the median of an even length arraylist
}
else
{
return((double)(int)al.get((al.size()/2))); // returns the median of an odd length arraylist
}
}
}