0️⃣python数据结构与算法学习路线 学习内容:
- 基本算法:枚举、排序、搜索、递归、分治、优先搜索、贪心、双指针、动态规划等…
- 数据结构:字符串(string)、列表(list)、元组(tuple)、字典(dictionary)、集合(set)、数组、队列、栈、树、图、堆等…
题目:
给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
找到所有在 [1, n] 范围之间没有出现在数组中的数字。
您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
输入输出:
输入:
[4,3,2,7,8,2,3,1]
输出:
[5,6]
解题思路:
判断数组中的数在range(1,N+1)中是否存在
算法实现:
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
return_list = []
counter = set(nums)
l = len(nums)
for i in range(1,l+1):
if i not in counter:
return_list.append(i)
return return_list
出现问题:
- Python 判断list是否为空
方式一:
list_temp = []
if len(list_temp):
#存在值即为真
else:
#list_temp是空的
方式二:
list_temp = []
if list_temp:
#存在值即为真
else:
#list_temp是空的 - Python 之列表添加元素的3种方法
追加单个值: append() 方法
>>> list = ['crazyit', 20, -2]
>>> list.append('fkit')
>>> print(list)
['crazyit', 20, -2, 'fkit']
追加元组、列表等:extend() 方法
>>> b_list = ['a', 30]
>>> b_list.extend((-2, 3.1))
>>> print(b_list)
['a', 30, -2, 3.1]
>>> a_list = (3.4, 5.6)
>>> b_list.extend(a_list)
>>> print(b_list)
['a', 30, -2, 3.1,3.4, 5.6]
列表中间增加元素:insert() 方法
>>> c_list = [1, 2, 3, 4, 5]
>>> c_list.insert(3, 'CRAZY' )
>>> print(c_list)
[1, 2, 3, 'CRAZY', 4, 5]
>>> c_list.insert(3, tuple('crazy'))
>>> print(c_list)
[1, 2, 3, ('c', 'r', 'a', 'z', 'y'), 'CRAZY', 4, 5] # 在索引3处插入元组,元组被当成一个元素