1+ /* *
2+ * 动态扩容的数组
3+ */
4+ class DynamicArray {
5+ companion object {
6+ // 默认容量
7+ const val DEFAULT_CAPACITY = 10
8+
9+ // 最大容量
10+ const val MAX_CAPACITY = Int .MAX_VALUE
11+ }
12+
13+ // 当前已使用大小
14+ private var usedSize = 0
15+
16+ // 当前容量大小
17+ private var capacity = 0
18+
19+ // 数组容器
20+ private var data: Array <Int >
21+
22+ init {
23+ this .capacity = DEFAULT_CAPACITY
24+ this .data = Array (this .capacity) { 0 }
25+ }
26+
27+ /* *
28+ * 增加元素
29+ */
30+ fun add (value : Int ) {
31+ if (this .usedSize == this .capacity - 1 ) {
32+ this .doubleCapacity()
33+ }
34+ this .data[this .usedSize] = value
35+ ++ this .usedSize
36+ }
37+
38+ /* *
39+ * 移除元素
40+ */
41+ fun remove (value : Int ) {
42+ if (this .usedSize >= 0 ) {
43+ var target = - 1
44+
45+ // 查找目标所在位置
46+ for (i in 0 until this .usedSize) {
47+ if (this .data[i] == value) {
48+ target = i
49+ break
50+ }
51+ }
52+
53+ // 找到了
54+ if (target >= 0 ) {
55+ val size = this .usedSize - 1
56+
57+ // 把后续元素往前搬
58+ for (i in target until size) {
59+ this .data[i] = this .data[i + 1 ]
60+ }
61+
62+ // 最后一个元素位置置为空
63+ this .data[size] = 0
64+
65+ // 更新已使用大小
66+ this .usedSize = size
67+ }
68+ }
69+ }
70+
71+ /* *
72+ * 通过索引设置元素的值
73+ */
74+ fun set (index : Int , value : Int ) {
75+ if (this .checkIndex(index)) {
76+ this .data[index] = value
77+ return
78+ }
79+
80+ throw IllegalArgumentException (" index must be in rang of 0..${this .usedSize} " )
81+ }
82+
83+ /* *
84+ * 获取元素
85+ */
86+ fun get (index : Int ): Int? {
87+ if (this .checkIndex(index)) {
88+ return this .data[index]
89+ }
90+
91+ throw IllegalArgumentException (" index must be in rang of 0..${this .usedSize} " )
92+ }
93+
94+ /* *
95+ * 获取当前数组的大小
96+ */
97+ fun getSize (): Int = this .usedSize
98+
99+ private fun checkIndex (index : Int ): Boolean {
100+ return index >= 0 && index < this .usedSize
101+ }
102+
103+ /* *
104+ * 按原容量的两倍进行扩容
105+ */
106+ private fun doubleCapacity () {
107+ if (this .capacity < MAX_CAPACITY ) {
108+ this .capacity = Math .min(this .capacity * 2 , MAX_CAPACITY )
109+ val newArray = Array (this .capacity) { 0 }
110+
111+ for (i in 0 until this .usedSize) {
112+ newArray[i] = this .data[i]
113+ }
114+
115+ this .data = newArray
116+ }
117+ }
118+ }
0 commit comments