title: LEETCODE DAY1:数组
date: 2024-02-22 13:54:30
tags:
#DAY1
今日题目:LEETCODE 704(二分查找)、27(移除元素)
附加题:34()、35()
##T704
写二分要注意的核心是考虑极端情况下数组中的每一个点是否都能被遍历到
一个简单的例子是如下图如果在elif处写成high=mid-1,会导致mid-1处的值无法被遍历到
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
low=0
high=len(nums)-1
while low <high :
mid=(low+high) //2
if nums[mid]< target:
low=mid+1
elif nums[mid]>target:
high=mid
else:
return mid
return -1
结果:测试用例nums=[5]未通过
修改代码为
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
low=0
high=len(nums)-1
while low <= high :
mid=(low+high) //2
if nums[mid]< target:
low=mid+1
elif nums[mid]>target:
high=mid-1
else:
return mid
return -1
成功AC
##T27
###Method 1(暴力法) #O(n^2)#时间复杂度
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
i=0
k=len(nums)
while i<k:
if nums[i]==val:
for j in range(i+1,k):
nums[j-1]=nums[j]
k-=1
else:
i+=1
return k
错误:思路没理清k-1应该不在循环里
改正后AC
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
i=0
k=len(nums)
while i<k:
if nums[i]==val:
for j in range(i+1,k):
nums[j-1]=nums[j]
k-=1
i-=1
i+=1
return k
细节上注意如果写成
for j in range(i,k):
nums[j]=nums[j+1]
会溢出报错
###METHOD2(双指针法)
第一遍错误
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
slow,fast=0,0
while fast < len(nums):
if nums[fast]==val:
fast+=1
nums[slow]=nums[fast]
else:
nums[slow]=nums[fast]
slow+=1
fast+=1
return slow
第二遍AC
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
slow,fast=0,0
while fast < len(nums):
if nums[fast]==val:
fast+=1
#nums[slow]=nums[fast]
else:
nums[slow]=nums[fast]
slow+=1
fast+=1
return slow
今日以恢复手感为主,做得较慢,同时学习了用markdown写博客,继续加油!
本文介绍了如何解决LeetCode上的两个问题:704号二分查找,重点在于处理极端情况下的数组遍历;以及27号移除元素,通过暴力法和双指针法的实现,包括常见错误和修正。作者还提到通过这个过程学习了Markdown写作。
541

被折叠的 条评论
为什么被折叠?



