• Array && Dynamic Array


    Array(数组)

    盛有单一类型固定数量值的容器类

    • 以0开始的索引
    • 有数组长度属性(长度不一定等于容器大小)
    • 内存表示(连续的)
    • 边界检查

    Dynamic Array(ADT 抽象数据类型)

    • 数组的容量动态可变
    • 存放的东西不限制类型

    自定义动态数组

    # -*- coding:utf-8 -*-
    # @Author :xuchaoqiang
    
    import ctypes
    
    
    class DynamicArray:
    
        def __init__(self):
            # Create an empty array
            self._n = 0  # size
            self._capacity = 10
            self._A = self._make_array(self._capacity)
    
        # len(list)
        def __len__(self):
            return self._n
    
        def is_empty(self):
            return self._n == 0
    
        # O(1)
        def __getitem__(self, k):
            if not 0 <= k < self._n:
                raise ValueError('invalid index')
            return self._A[k]
    
        # O(1)
        def append(self, obj):
            if self._n == self._capacity:
                self._resize(2 * self._capacity)
            self._A[self._n] = obj
            self._n += 1
    
        def _make_array(self, c):
            return (c * ctypes.py_object)()
    
        def _resize(self, c):
            B = self._make_array(c)
            for k in range(self._n):
                B[k] = self._A[k]
            self._A = B
            self._capacity = c
    
        # O(n)
        def insert(self, k, value):
            if self._n == self._capacity:
                self._resize(2 * self._capacity)
            for j in range(self._n, k, -1):
                self._A[j] = self._A[j - 1]
            self._A[k] = value
            self._n += 1
    
        # O(n)
        def remove(self, value):
            for k in range(self._n):
                if self._A[k] == value:
                    for j in range(k, self._n - 1):
                        self._A[j] = self._A[j + 1]
                    self._A[self._n - 1] = None
                    self._n -= 1
                    return
            raise ValueError('value not found')
    
        def _print(self):
            for i in range(self._n):
                print(self._A[i], end=' ')
            print()
    
    
    if __name__ == '__main__':
        mylist = DynamicArray()
        print('size was: ', str(len(mylist)))
        mylist.append(10)
        mylist.append(20)
        mylist.append(30)
        mylist.insert(0, 0)
        mylist.insert(1, 5)
        mylist.insert(3, 15)
        mylist._print()
        mylist.remove(20)
        mylist._print()
    
        print('size is: ', str(len(mylist)))

    Python List各个操作的时间复杂度

     

  • 相关阅读:
    【HDU3032】Nim or not Nim?(博弈论)
    【BZOJ1022】小约翰的游戏(博弈论)
    【HDU1848】Fibonacci again and again(博弈论)
    【POJ1704】Georgia and Bob(博弈论)
    【BZOJ1299】巧克力棒(博弈论,线性基)
    【Luogu2197】NIM游戏(博弈论)
    【洛谷2252&HDU1527】取石子游戏(博弈论)
    【HDU1846】Brave Game(博弈论)
    【CF888G】Xor-MST(最小生成树,Trie树)
    长链剖分学习笔记
  • 原文地址:https://www.cnblogs.com/Xuuuuuu/p/12845274.html
Copyright © 2020-2023  润新知