最大限の効率を得るには、おそらく循環バッファーを実装するカスタム クラスになります。
データを保持するために、インスタンス化時に固定サイズの配列を作成するだけです。さらに、開始インデックス、サイズ メンバー、および容量があるため、バッファー内のデータ量と開始位置がわかります。
したがって、まず、リストにはデータが含まれておらず、開始位置は 0、サイズは 0 です。
アイテムを追加すると、要素に入り、(start + size) % capacity
まだsize
にない場合はインクリメントされcapacity
ます。だった場合はcapacity
、同様にインクリメントしstart
、必要に応じて次のようにラップしますstart = (start + 1) % capacity
。
リストからindex の要素を取得するにはn
、実際に次のように調整しますstart
。
return element[(start + n) % capacity];
リストの先頭を削除することは仕様にないため、カバーしていません。ただし、 が 0 でないことを確認するのは簡単なチェックであり、次にsize
でアイテムを抽出し、上記と同じラップアラウンドでelement[start]
インクリメントします。start
疑似コード (テストされていませんが、近いはずです):
def listNew (capacity):
me = new object
me.capacity = capacity
me.data = new array[capacity]
me.start = 0
me.size = 0
return me
def listAdd (me, item):
if me.size = me.capacity:
me.data[me.start] = item
me.start = (me.start + 1) % me.capacity
else:
me.data[(me.start + me.size) % me.capacity] = item
me.size = me.size + 1
def listGet (me, index):
if index > size:
return 0 # or raise error of some sort
return me.data[(me.start + index) % me.capacity]
def listRemove (me):
if size == 0:
return 0 # or raise error of some sort
item = me.data[(me.start + index) % me.capacity]
me.start = (me.start + 1) % me.capacity
me.size = me.size - 1
return item
これらの操作はすべて、要求に応じて O(1) 時間の複雑さです。
1
数字を8
5 要素のリストに追加する特定の例では、次のようになります。
0 1 2 3 4 <--- index
+---+---+---+---+---+
| 6 | 7 | 8 | 4 | 5 |
+---+---+---+---+---+
^
+--------- start = 3
size = 5
capacity = 5
そうすれば、バッファから仮想インデックス 3 (4 番目の数字) を抽出すると、次の実際のインデックスが得られます。
(start + 3) % capacity
= ( 3 + 3) % 5
= 6 % 5
= 1