-
Notifications
You must be signed in to change notification settings - Fork 0
/
array.go
50 lines (44 loc) · 799 Bytes
/
array.go
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
package link
type MyArray struct {
List []int
Len int
Cap int
}
func NewMyArray(cap int) *MyArray {
return &MyArray{
List: make([]int, cap),
Len: 0,
Cap: cap,
}
}
func (ma *MyArray) Insert(value int, pos int) {
if pos >= 0 && pos < ma.Cap {
ma.Len++
if ma.Len == ma.Cap {
newList := make([]int, ma.Cap*2)
for i := 0; i < ma.Len; i++ {
newList[i] = ma.List[i]
}
ma.List = newList
ma.Cap = ma.Cap * 2
}
for i := ma.Len; i > pos; i-- {
ma.List[i] = ma.List[i-1]
}
ma.List[pos] = value
}
}
func (ma *MyArray) Del(pos int) {
if pos >= 0 && pos < ma.Len {
for i := pos; i < ma.Len-1; i++ {
ma.List[i] = ma.List[i+1]
}
ma.Len--
}
}
func (ma *MyArray) Get(pos int) int {
if pos >= 0 && pos < ma.Len {
return ma.List[pos]
}
return 0
}