【手把手带你刷Leetcode力扣】2.数据结构 - 数组

数组:

连续的内存空间中,存储一组相同类型的元素


区分

  • 元素
  • 索引 — (从0开始)
  • 数组访问(Access) — 通过索引取得某个元素的值a[1]
  • 数组搜索(Search) — 遍历数组搜索某个元素且可返回索引

时间复杂度

  • 访问Access — O(1)
  • 搜索Search — O(N)
  • 插入Insert — O(N)
  • 删除Delete — O(N)

特点

  • 适合读
  • 不适合写
  • 读多写少

常用操作

  1. 创建数组
    a = []

  2. 添加元素
    a.append()
    (添加的元素)
    数组后还有空间O(1);无空间O(N)

    a.insert(2, 99)
    (插入的索引,插入的元素)
    O(N)

  3. 访问元素
    temp = a[2]

  4. 修改元素
    a[2] = 88

  5. 删除元素
    a.remove(88)
    (删除的元素)
    O(N)

    a.pop(1)
    (删除的索引)
    O(N)

    a.pop()
    删除最后一个元素
    O(1)

  6. 遍历数组
    for i in a:
    i为元素

    for index, element in enumerate(a):

    for i in range(0, len(a)):
    i为索引

  7. 查找元素
    index = a.index(2)
    (查找的元素)
    返回索引
    O(N)

  8. 数组的长度
    size = len(a)

  9. 数组排序(内置的排序方法)
    a.sort()
    从小到大
    a.sort(reverse=True)
    从大到小
    O(NlogN)


练习题

  • 485 . 最大连续1的个数
class Solution:
	# One pass
	# N is the size of nums
	# Time Complexity: O(N)
	# Space Complexity: O(1)
	def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
		if nums is None or len(nums) == 0:
			return 0
		
		count = 0
		result = 0
		for num in nums:
			if num == 1:
				count += 1
			else:
				result = max(result, count)
				count = 0
				
		return max(result, count)
  • 283 . 移动0
class Solution:
	# One pass
	# N is the size of nums
	# Time Complexity: O(N)
	# Space Complexity: O(1)
	def moveZeros(self, nums: List[int]) -> None:
	index = 0
	for num in nums:
		if num != 0:
			nums[index] = num
			index += 1
	for i in range(index, len(nums)):
		nums[i] = 0
  • 27 . 移除元素 — 双指针解法
class Solution:
	# Two pointers
	# N is the size of nums
	# Time complexity: O(N)
	# Space complexity: O(1)
	def removeElement(self, nums: List[int], val: 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

学习视频来源B站—爱学习的饲养员—手把手带你刷Leetcode力扣

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值