Day1
mySqrt
因为太菜了所以要坚持刷题,否则申不到实习了呜呜呜。
欢迎大家关注,一起刷题!
class Solution:
def mySqrt(self, x: int) -> int:
if x==1:
return 1
temp=int(x/2)
up=x
down=0
while(1):
if temp*temp<=x:
down=temp
else:
up=temp
if temp*temp<=x and (temp+1)*(temp+1)>x:
return int(temp)
temp=int(down+(up-down)/2)
关键点:
- int转换,虽然输入x为int,x/2还是会变成double
- tie:注意考虑等号
searchInsert
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
if target<nums[0] or target==nums[0]:
return 0
index=int(len(nums)/2)
middle=nums[index]
up=len(nums)
down=0
while(1):
if middle==target:
return index
elif target<middle:
up=index
else:
down=index
if up-down==1:
return up
index=int(down+(up-down)/2)
middle=nums[index]
思路:多种情形
- 能够找到的
- 需要插入的:开头插入的,中间插入的,结尾插入的(后两种合在一起)
现在还不大能想全,很多edge case都要带进去才能考虑全,所以写得有些慢。加油啦!
//update:
发现Python神仙模块bisect
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
return bisect.bisect_left(nums,target)
直接return这个函数就能过,笑死我了