数组理论基础
文章链接:代码随想录
题目建议: 了解一下数组基础,以及数组的内存空间地址,数组也没那么简单。
704. 二分查找 ✅
题目建议: 大家能把 704 掌握就可以,35.搜索插入位置 和 34. 在排序数组中查找元素的第一个和最后一个位置 ,如果有时间就去看一下,没时间可以先不看,二刷的时候在看。
先把 704写熟练,要熟悉 根据 左闭右开,左闭右闭 两种区间规则 写出来的二分法。
题目链接:. - 力扣(LeetCode)
文章讲解:代码随想录
视频讲解:手把手带你撕出正确的二分法 | 二分查找法 | 二分搜索法 | LeetCode:704. 二分查找_哔哩哔哩_bilibili
# 704
# 左闭右闭
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left = 0
right = len(nums) - 1
while left <= right:
middle = (left + right)/2
if nums[middle] > target:
right = middle - 1
elif nums[middle] < target:
left = middle + 1
else:
return middle
return -1
# 704
# 左闭右开
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left = 0
right = len(nums)
while left < right:
middle = (left + right)/2
if nums[middle] > target:
right = middle
elif nums[middle] < target:
left = middle + 1
else:
return middle
return -1
- 35.搜索插入位置(opens new window)✅
- 34.在排序数组中查找元素的第一个和最后一个位置(opens new window)AC
- 69.x 的平方根(opens new window)⌛️
- 367.有效的完全平方数(opens new window)⌛️
# 35
# 左闭右闭
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left, right = 0, len(nums)-1
while left <= right:
middle = left + ((right - left) / 2); # 防止溢出,等同于(left + right)/2
if nums[middle] > target:
right = middle - 1
elif nums[middle] < target:
left = middle + 1
else:
return middle
return right + 1 # middle + 1适用于两种区间
# 目标值在数组所有元素之前 [0, -1]
# 目标值等于数组中某一个元素 return middle;
# 目标值插入数组中的位置 [left, right],return right + 1
# 目标值在数组所有元素之后的情况 [left, right], 因为是右闭区间,所以 return right + 1
# 35
# 左闭右开
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left, right = 0, len(nums)
while left < right:
middle = left + ((right - left) / 2); # 防止溢出,等同于(left + right)/2
if nums[middle] > target:
right = middle
elif nums[middle] < target:
left = middle + 1
else:
return middle
return right # middle + 1适用于两种区间
# 目标值在数组所有元素之前 [0,0)
# 目标值等于数组中某一个元素 return middle
# 目标值插入数组中的位置 [left, right) ,return right 即可
# 目标值在数组所有元素之后的情况 [left, right),因为是右开区间,所以 return right
34再想一下情况三这里,因为这里元素可能重复,思路和查找有点不一致。
leftBoder + 1, rightBoder - 1
27. 移除元素✅
题目建议: 暴力的解法,可以锻炼一下我们的代码实现能力,建议先把暴力写法写一遍。 双指针法 是本题的精髓,今日需要掌握,至于拓展题目可以先不看。
题目链接:. - 力扣(LeetCode)
文章讲解:代码随想录
视频讲解:数组中移除元素并不容易! | LeetCode:27. 移除元素_哔哩哔哩_bilibili
# 27
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
slow = 0
for fast in range(len(nums)):
if nums[fast] != val:
nums[slow] = nums[fast]
slow += 1
return slow
该实现方法并没有改变元素的相对位置!
- 26.删除排序数组中的重复项(opens new window)⌛️
- 283.移动零(opens new window)⌛️
- 844.比较含退格的字符串(opens new window)⌛️
- 977.有序数组的平方(opens new window)⌛️