forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharray.php
142 lines (130 loc) · 2.83 KB
/
array.php
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
<?php
/**
* Created by PhpStorm.
* User: leo
* Date: 2018/10/5
* Time: 9:13
*/
/**
* 简单数组类
*/
class MyArray
{
//数据
private $data;
//容量
private $capacity;
//长度
private $length;
/**
* MyArray constructor.
* @param $capacity
*/
public function __construct($capacity)
{
$capacity = intval($capacity);
if($capacity <= 0) {
return null;
}
$this->data = array();
$this->capacity = $capacity;
$this->length = 0;
}
/**
* 数组是否已满
* @return bool
*/
public function checkIfFull()
{
if($this->length == $this->capacity) {
return true;
}
return false;
}
/**
* 判断索引index是否超出数组范围
* @param $index
* @return bool
*/
private function checkOutOfRange($index)
{
if($index >= $this->length) {
return true;
}
return false;
}
/**
* 在索引index位置插入值value,返回错误码,0为插入成功
* @param $index
* @param $value
* @return int
*/
public function insert($index, $value)
{
$index = intval($index);
$value = intval($value);
if ($index < 0) {
return 1;
}
if ($this->checkIfFull()) {
return 2;
}
for ($i = $this->length - 1; $i >= $index; $i--) {
$this->data[$i + 1] = $this->data[$i];
}
$this->data[$index] = $value;
$this->length++;
return 0;
}
/**
* 删除索引index上的值,并返回
* @param $index
* @return array
*/
public function delete($index)
{
$value = 0;
$index = intval($index);
if ($index < 0) {
$code = 1;
return [$code, $value];
}
if ($this->checkOutOfRange($index)) {
$code = 2;
return [$code, $value];
}
$value = $this->data[$index];
for ($i = $index; $i < $this->length - 1; $i++) {
$this->data[$i] = $this->data[$i + 1];
}
$this->length--;
return [0, $value];
}
/**
* 查找索引index的值
* @param $index
* @return array
*/
public function find($index)
{
$value = 0;
$index = intval($index);
if ($index < 0) {
$code = 1;
return [$code, $value];
}
if ($this->checkOutOfRange($index)) {
$code = 2;
return [$code, $value];
}
return [0, $this->data[$index]];
}
public function printData()
{
$format = "";
for ($i = 0; $i < $this->length; $i++) {
$format .= "|" . $this->data[$i];
}
print($format . "\n");
}
}