数组
实现一个支持动态扩容的数组
import ctypes
# provides low-level arrays
class DynamicArray:
"""A dynamic array class akin to a simplified Python list."""
def __init__(self, capacity=1):
"""Create an empty array."""
self._n = 0
self._capacity = capacity
self._A = self._make_array(self._capacity)
# count actual elements # default array _capacity # low-level array
def __len__(self):
"""Return number of elements stored in the array."""
return self._n
def __str__(self):
return str(self._A)
def __getitem__(self, k):
"""Return element at index k."""
if not 0 <= k < self._n:
raise IndexError('invalid index')
return self._A[k] # retrieve from array
def append(self, obj):
"""Add object to end of the array."""
if self._n == self._capacity:
# not enough room # so double _capacity
self._resize(2*self._capacity)
self._A[self._n] = obj
self._n += 1
def _resize(self, c):
# nonpublic utitity
"""Resize internal array to _capacity c."""
B = self._make_array(c)
for k in range(self._n):
B[k] = self._A[k]
self._A = B
self._capacity = c
# new (bigger) array # for each existing value
# use the bigger array
def _make_array(self, c):
# nonpublic utitity
"""Return new array with _capacity c."""
return (c * ctypes.py_object)() # see ctypes documentation
dynamic_a = DynamicArray(3)
dynamic_a.append(1)
dynamic_a.append(2)
dynamic_a.append(3)
dynamic_a.append(4)
print(len(dynamic_a))
实现一个大小固定的有序数组,支持动态增删改操作
其实不太知道什么叫动态增删,按着自己的理解写了一下。
class SortedList():
""" sorted list with fixed length"""
def __init__(self, length):
self.list = []
self.length = length
self._last = 0 # index of the next new element in the list
def append(self, x):
""" append one item"""
if self._last >= self.length:
print("Overflow!")
return -1
else:
self.list.append(x)
self.list = sorted(self.list)
self._last += 1
return self.list
def remove(self, i):
"""remove the ith item"""
if i < self._last - 1:
for i in range(i, self.length - 1):
self.list[i] = self.list[i+1]
self.list.pop()
elif i == self._last + 1:
self.list.pop()
else:
print("Out of index!")
def __str__(self):
str_list = [str(x) for x in self.list]
return ", ".join(str_list)
if __name__ == '__main__':
sorted_l = SortedList(4)
sorted_l.append(2)
sorted_l.append(5)
sorted_l.append(1)
sorted_l.append(0)
print(sorted_l)
sorted_l.append(3)
sorted_l.remove(2)
print(sorted_l)
实现两个有序数组合并为一个有序数组
a = [1, 3, 5]
b = [2, 4, 6]
c = sorted(a + b)
print(c)
两数之和
def twoSum3(nums, target):
dict_nums = {nums[i]:i for i in range(len(nums))}
print("dict_nums", dict_nums)
for a in range(len(nums)):
one_unm = nums[a]
other_one = target - one_unm
if other_one in dict_nums and a!= dict_nums[other_one]:
return [a,dict_nums[other_one]]
字典在生成的时候,如果遇到重复的key,后一个会把前一个覆盖掉,通常被认为是个缺点,但在这里很好地利用了这个特性,解决了6=3+3这种重复数字的情况。
链表
实现单链表、循环链表、双向链表,支持增删操作
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
class LinkedList(object):
def __init__(self):
self.head = None
def __len__(self):
pre = self.head
length = 0
while pre:
length += 1
pre = pre.next
return length
def is_empty(self):
return False if len(self) > 0 else True
def append(self, data):
node = Node(data)
if self.head is None:
self.head = node
else:
pre = self.head
while pre.next:
pre = pre.next
pre.next = node
def insert(self, index, data):
node = Node(data)
if abs(index + 1) > len(self):
return False
index = index if index >= 0 else len(self) + index + 1
if index == 0:
node.next = self.head
self.head = node
else:
pre = self.get(index - 1)
if pre:
nex = pre.nex
pre.nex = node
node.next = nex
else:
return False
return node
def delete(self, index):
f = index if index > 0 else abs(index + 1)
if len(self) <= f:
return False
pre = self.head
index = index if index >= 0 else len(self) + index
prep = None
while index:
prep = pre
pre = pre.nex
index -= 1
if not prep:
self.head = pre.nex
else:
prep.nex = pre.nex
return pre.data
l = LinkedList()
l.insert(0, 1)
print("length", len(l))
实现单链表反转
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
class LinkedList(object):
def __init__(self):
self.head = None
def __reversed__(self):
def reverse(pre_node, node):
if pre_node is self.head:
pre_node.nex = None
if node:
next_node = node.nex
node.nex = pre_node
return reverse(node, next_node)
else:
self.head = pre_node
return reverse(self.head, self.head.nex)
实现两个有序的链表合并为一个有序链表
def Merge(self, pHead1, pHead2):
if pHead1 == None:
return pHead2
elif pHead2 == None:
return pHead1
pMergedHead = None
if pHead1.val < pHead2.val:
pMergedHead = pHead1
pMergedHead.next = self.Merge(pHead1.next, pHead2)
else:
pMergedHead = pHead2
pMergedHead.next = self.Merge(pHead1, pHead2.next)
return pMergedHead
实现求链表的中间结点
class Node:
def __init__(self,data,next):
self.data = data
self.next = next
n1 = Node('n1',None)
n2 = Node('n2',n1)
n3 = Node('n3',n2)
n4 = Node('n4',n3)
n5 = Node('n5',n4)
p1 = n5
p2 = n5
while p2.next is not None and p2.next.next is not None:
p1 = p1.next
p2 = p2.next.next
print(p1.data)