-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArray.go
More file actions
88 lines (74 loc) · 1.54 KB
/
Copy pathArray.go
File metadata and controls
88 lines (74 loc) · 1.54 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
package array
import (
"errors"
"fmt"
)
type Array struct {
data []int
length uint
}
func NewArray(capacity uint) *Array {
if capacity == 0 {
return nil
}
return &Array{
data: make([]int, capacity),
length: 0,
}
}
func (this *Array) Len() uint {
return this.length
}
func (this *Array) isArrayFull() bool {
return this.Len() == uint(cap(this.data))
}
func (this *Array) setSize() error {
capacity := uint(cap(this.data))
capacity = 2 * capacity
newData := make([]int, capacity)
for i := uint(0); i < this.Len(); i++ {
newData[i] = this.data[i]
}
this.data = newData
return nil
}
func (this *Array) Insert(index uint, v int) error {
// 判断array 是否full
if this.isArrayFull() {
// return errors.New("array is full")
this.setSize()
}
if index > this.Len() {
return errors.New("index is out of range")
}
for i := this.Len(); i >= index+1; i-- {
this.data[i] = this.data[i-1]
}
this.data[index] = v
this.length++
return nil
}
func (this *Array) Delete(index uint) (int, error) {
if index >= this.Len() {
return 0, errors.New("index is out of range")
}
v := this.data[index]
for i := index + 1; i < this.Len()-1; i++ {
this.data[i] = this.data[i+1]
}
this.length--
return v, nil
}
func (this *Array) Find(index uint) (int, error) {
if index >= this.Len() {
return 0, errors.New("index is out of range")
}
return this.data[index], nil
}
func (this *Array) Print() {
var format string
for i := uint(0); i < this.Len(); i++ {
format += fmt.Sprintf("|%+v", this.data[i])
}
fmt.Println(format)
}