


Operation | Average Time Complexity | Worst Time Complexity |
Search | ||
Insert | ||
Insert (at the end) | ||
Remove | ||
Remove (at the end) |

def search(arr: int[], target: int, length: int): for i in range(length): if arr[i] == target: return i return -1

def insert(arr: int[], index: int, value: int, length: int): # 最後の要素からindexまで右にシフトする for i in range(length-1, index-1, -1): arr[i+1] = arr[i] arr[index] = value

def insert_at_the_end(arr: int[], value: int, length: int): # ここではarrのサイズは一旦考えない arr[length] = value

def remove(arr: int[], index: int, length): # 消したい要素のindex+1から最後まで左に要素をシフトする for index in range(index + 1, length): arr[index - 1] = arr[index] # 最後の要素を削除する arr[length - 1] = null

def remove_at_the_end(arr: int[], length: int): if length > 0: # 最後の要素を削除する arr[length - 1] = null
# 配列の最後の位置に要素を挿入する def append(self, value: int): # 配列が既に全て埋まっている場合は、サイズを拡張する if self.length == self.capacity: self.resize() # 次の空いている位置に要素を挿入します self.arr[self.length] = value self.length += 1 def resize(self): # サイズを2倍にした新しい配列を作成します self.capacity = 2 * self.capacity newArr = [0] * self.capacity # 既存の全ての要素を新しい配列にコピーします for i in range(self.length): newArr[i] = self.arr[i] self.arr = newArr
# リストの作成 array = [1, 2, 3, 4, 5] # リストへの要素の追加 (O(1)) array.append(6) # array: [1, 2, 3, 4, 5, 6] # リストの特定位置への要素の挿入 (O(n) - n is the number of elements to shift) array.insert(0, 0) # array: [0, 1, 2, 3, 4, 5, 6] # リストからの要素の削除 (O(n) - n is the number of elements to shift) array.remove(3) # array: [0, 1, 2, 4, 5, 6] # リストの特定のインデックスの要素の取得 (O(1)) print(array[2]) # Output: 2 # リストの長さの取得 (O(1)) print(len(array)) # Output: 6 # リストから最後の要素を削除 (O(1)) last_element = array.pop() # last_element: 6, array: [0, 1, 2, 4, 5]
# 文字列の作成 string = "Hello, World!" # 文字列の連結 (O(n+m) - n and m are lengths of the strings) string += " How are you?" # string: "Hello, World! How are you?" # 文字列の特定のインデックスの文字の取得 (O(1)) print(string[0]) # Output: 'H' # 文字列の長さの取得 (O(1)) print(len(string)) # Output: 29 # 文字列の分割 (O(n) - n is the number of characters in the string) print(string.split(' ')) # Output: ['Hello,', 'World!', 'How', 'are', 'you?']
StringBuilderのような要素はないので、listとjoinを活用する事で文字列の連結時の時間計算量をにする事ができます。class StringBuilder: def __init__(self): self._strings = [] def append(self, string): self._strings.append(string) def to_string(self): return "".join(self._strings) sb = StringBuilder() # 文字列の連結 (O(1)) sb.append("Hello, ") # 文字列の連結 (O(1)) sb.append("World!") print(sb.to_string()) # Output: "Hello, World!"