数组操作的时间复杂度
1.Access O(1)
2.Search O(N)
3.Insert O(N)
4.Delete O(n) a.remove(元素)时间复杂度O(N) a.pop(索引)时间复杂度也是O(n) a.pop()删除最后一个元素 时间复杂度是O(1)
特点:适合读 不适合写 (读多写少)
遍历数组的三个方法
for i in a:
print(i)
for index, element in enumerate(a): # enumerate 返回索引 和值
print("Index at", index, "is", element)
for i in range(0, len(a)):
print("i:", i, "element:", a[i])
查找某个元素
a = [1, 2, 3]
index = a.index(2) 返回 1 (查找值返回index)时间复杂度也是O(n)
数组排序
a.sort(reverse = True or False)
485
我的答案:
class Solution(object):
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = 0
b = 0
for i in nums:
if i == 1:
a += i
else:
b = max(a, b)
a = 0
return max(a, b)
当时还有一种想法是数组按0切分 然后max len 但没实现出来
后来评论里看到了这种方法
先将数组转为str 然后按0split
这是后来写出的代码 时间复杂度比方法1高很多
class Solution(object):
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
s = ''
for i in nums:
s += str(i)
a = s.split('0')
c = 0
for m in a:
c = max(c, len(m))
return c
总结 以后再遇到取迭代数中最大或者最小一个 先创造一个新变量 赋值为0 然后新变量等于max(新变量,迭代出的数值)
这样就可以将循环从头到尾的数依次比较大小 取出最大最小值
283
本人代码:
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
index = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[index] = nums[i]
index += 1
for i in range(index, len(nums)):
nums[i] = 0
和其他答案差不多
也想过直接用remove 和 append做 依旧没有做出来
别人直接
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
for i in range(nums.count(0)):
nums.remove(0)
nums.append(0)
但很费时
总结:感觉循环用的还是不是很熟练
27
我的代码:
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
for i in reversed(range(len(nums))):
if nums[i] == val:
nums.remove(nums[i])
return len(nums)
这个很快就提交了 之前用的 pop 改成remove要快一些
重点在reversed 在循环的下面涉及到删除时 删除一个索引所对应的值后 python会自动吧删除的位置补上来 这样就会导致从删除位位置开始现在索引和原索引相差1个 会报错 所以只要reverse一下 就好了
别人的双指针算法:
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
if nums is None or len(nums) == 0:
return 0
l, r = 0, len(nums) - 1
while l < r:
while (l < r and nums[l] != val):
l += 1
while (l < r and nums[r] == val):
r -= 1
nums[l], nums[r] = nums[r], nums[l]
return l if nums[l] == val else l + 1
没有我的好 且比我复杂