forked from liuyubobobo/Play-with-Algorithm-Interview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMyVector.java
67 lines (50 loc) · 1.67 KB
/
MyVector.java
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
import java.util.Arrays;
/**
* Created by liuyubobobo.
*/
public class MyVector<Item> {
private Item[] data;
private int size; // 存储数组中的元素个数
private int capacity; // 存储数组中可以容纳的最大的元素个数
public MyVector(){
data = (Item[])new Object[100];
size = 0;
capacity = 100;
}
// 平均复杂度为 O(1)
public void push_back(Item e){
if(size == capacity)
resize(2 * capacity);
data[size++] = e;
}
// 平均复杂度为 O(1)
public Item pop_back(){
if(size <= 0)
throw new IllegalArgumentException("can not pop back for empty vector.");
size --;
return data[size];
}
// 复杂度为 O(n)
private void resize(int newCapacity){
assert newCapacity >= size;
Item[] newData = (Item[])new Object[newCapacity];
for(int i = 0 ; i < size ; i ++)
newData[i] = data[i];
data = newData;
capacity = newCapacity;
}
// 注意:Java语言由于JVM内部机制的因素,测量的性能时间有可能是跳跃不稳定的。
public static void main(String[] args) {
for( int i = 10 ; i <= 26 ; i ++ ){
int n = (int)Math.pow(2,i);
long startTime = System.currentTimeMillis();
MyVector<Integer> vec = new MyVector<Integer>();
for(int num = 0 ; num < n ; num ++){
vec.push_back(num);
}
long endTime = System.currentTimeMillis();
System.out.print(n + " operations: \t");
System.out.println((endTime - startTime) + " ms");
}
}
}