Определение
Массив PHP по умолчанию является динамической структурой данных, и базовый массив должен открывать в памяти пространство с фиксированной емкостью для хранения непрерывного раздела данных, поэтому мы можем использовать splfixedarray только для ограничения объема памяти.
Код
Адрес GitHub: массивы
class Arrays
{
private $data;
private $size;
private $capacity;
//Constructor, pass in the capacity of array, construct array, default capacity of array capacity = 10
public function __construct(int $capacity = 10)
{
$this->data = new SplFixedArray($capacity);
$this->capacity = $capacity;
$this->size = 0;
}
//Get the number of elements in the array
public function getSize():int
{
return $this->size;
}
//Returns whether the array is empty
public function isEmpty():bool
{
return $this->size == 0;
}
//Get the capacity of an array
public function getCapacity():int
{
return $this->data->getSize();
}
//Insert a new element E O (n) at the index index
public function add(int $index,int $e)
{
if($index <0 || $index > $this->size){
throw new Exception("index is illegal");
}
if ($this->size == $this->capacity){
$this->resize(2 * $this->capacity);
}
for ($i=$this->size -1 ; $i >=$index; $i--) {
$this->data[$i + 1] = $this->data[$i];
}
$this->data[$index] = $e;
$this->size ++;
}
//Add a new element o after all elements (1)
public function addLast($e)
{
$this->add($this->size,$e);
}
//Add a new element o before all elements
public function addFirst($e)
{
$this->add(0,$e);
}
//Get element o of index location (1)
public function get($index)
{
if($index <0 || $index > $this->size){
throw new Exception("index is illegal");
}
return $this->data[$index];
}
public function getLast(){
return $this->get($this->size-1);
}
public function getFirst(){
return $this->get(0);
}
//Change the element of index index location to e o (1)
public function set($index,$e)
{
if($index <0 || $index > $this->size){
throw new Exception("index is illegal");
}
$this->data[$index] = $e;
}
//Find if there is element E O in the array (n)
public function contains($e):bool
{
for ($i=0; $i < $this->size; $i++) {
if($this->data[$i] == $e){
return true;
}
}
return false;
}
//Finds the index of element E in the array, and returns - 1 o (n) if element E does not exist
public function find($e):int
{
for ($i=0; $i < $this->size; $i++) {
if($this->data[$i] == $e){
return $i;
}
}
return -1;
}
//Delete the element at index position from the array, and return the deleted element
public function remove($index)
{
if($index <0 || $index > $this->size){
throw new Exception("index is illegal");
}
$ret = $this->data[$index];
for ($i=$index+1; $i < $this->size; $i++) {
$this->data[$i-1] = $this->data[$i];
}
$this->size--;
unset($this->data[$this->size]);
if($this->size == $this->capacity / 4 && $this->capacity /2 != 0){
$this->resize($this->capacity/2);
}
return $ret;
}
//Delete the last element from the array, return the deleted element
public function removeLast()
{
$this->remove($this->size-1);
}
//Delete the first element from the array, return the deleted element
public function removeFirst()
{
$this->remove(0);
}
//Remove element E from array
public function removeElement($e)
{
$index = $this->find($e);
if($index != -1){
$this->remove($index);
}
}
//Change the capacity of array space to newcapacity
private function resize($newCapacity)
{
$newData = (new self($newCapacity))->data;
for($i=0;$i<$this->size;$i++){
$newData[$i] = $this->data[$i];
}
$this->data = $newData;
$this->capacity = $newCapacity;
}
public function __toString()
{
$str = sprintf("\nArray: size = %d , capacity = %d\n",$this->size,$this->getCapacity());
$str.='[';
for($i = 0 ; $i < $this->size; $i ++){
$str.= $i;
if($i != $this->size - 1){
$str.= ", ";
}
}
$str.="]";
return $str;
}
}Временная сложность
| Аддитивные элементы | В худшем случае снова переместите все позиции элементов | добавлять | O(n) |
| Добавьте элементы в заголовок | Наихудший сценарий | Добавить сначала | O(n) |
| Добавьте элементы в конце | В лучшем случае | addLast | O(1) |
| Добавьте элементы в конце | Данные являются непрерывными, и элементы могут быть получены непосредственно в соответствии с местоположением | получить | O(1) |
| Получить первый элемент | То же | getFirst | O(1) |
| Получить конечный элемент | То же | получить Последнее | O(1) |
| Измените элемент в указанном местоположении индекса | То же | набор | O(1) |
| Найдите, есть ли элементы в массиве | Требуется круговой поиск | содержит | O(1) |
| Найдите индекс элемента в массиве | Требуется круговой поиск | находить | O(1) |
| Удалить указанный элемент | В худшем случае снова переместите все позиции элементов | удалить | O(n) |
| Удалить первый элемент | Наихудший сценарий | Удалить первым | O(n) |
| Удалить конечный элемент | В лучшем случае | Удалить последние | O(1) |
| Удалить указанный элемент | Требуется круговой поиск | Удалить элемент | O(1) |
резюме
Массив-это самая базовая структура данных, поэтому понимание принципа массива и сложности времени работы является основой структуры и алгоритма глубокого обучения данным.
Добро пожаловать, чтобы отсканировать QR-код ниже и привлечь ваше внимание:
Интернет-инженер (идентификатор: php stcn), мы учимся и прогрессируем вместе