小李飞刀:刷题第五弹!

5次阅读

共计 1749 个字符,预计需要花费 5 分钟才能阅读完成。

写在前面的话
好几天木有刷题啦,今天猛刷了一把,要梳理一个顺序好好的学习啦~ 一定要好好执行每天做题的计划!最近真的好忙碌啊,还要做视频。不过呢,看了高效学习的书,感觉其实不能说太分散的学习,应该考虑多方面的联系,形成整体性的学习,还得琢磨琢磨 … 小李加油呀!
认真做题
第一题
58. 最后一个单词的长度难度:简单给定一个仅包含大小写字母和空格 ‘ ‘ 的字符串,返回其最后一个单词的长度。如果不存在最后一个单词,请返回 0。说明:一个单词是指由字母组成,但不包含任何空格的字符串。我的题解:
class Solution(object):
def lengthOfLastWord(self, s):
“””
:type s: str
:rtype: int
“””
lastindex = 0
res = 0
for i in s:
if i == ‘ ‘:
lastindex = 0
else:
lastindex = lastindex + 1
if lastindex > 0:
res = lastindex
return res
方法的效率不是太高。
解题思路:每次遇到空格的时候,单词的长度就置空,不是的话就加 1,然后用 res 记录上一次的 lastindex 长度。其他这题也要再多刷一次。
第二题
53. 最大子序和难度:简单给定一个整数数组 nums,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。我的题解:
class Solution(object):
def maxSubArray(self, nums):
“””
:type nums: List[int]
:rtype: int
“””
maxSum = nums[0]
sum = 0
for i in nums:
sum = sum + i
if sum > maxSum:
maxSum = sum
if sum < 0:
sum = 0
return maxSum

解题思路:这题是参考了小佳扬的思路。重点考虑什么时候会有最大的值。maxSum 其实相当于一个记住上次最大值的点,sum 则是移动的点。当遇到会导致总和小于 0 的值,那一定是要排除的,因为肯定会拉低总和大小。其他:这次还要多考虑情况,然后再刷一次。
第三题
35. 搜索插入位置难度:简单给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。我的题解:
class Solution(object):
def searchInsert(self, nums, target):
“””
:type nums: List[int]
:type target: int
:rtype: int
“””
length = len(nums)
for i in range(length):
if nums[i] == target:
return i
if nums[i] > target:
nums.insert(i,target)
return i
nums.append(target)
return length

解题思路:用了 insert 的办法,找到对应的 Index 之后插入即可。
第四题
28. 实现 strStr() 难度:简单实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从 0 开始)。如果不存在,则返回 -1。我的题解:
class Solution(object):
def strStr(self, haystack, needle):
“””
:type haystack: str
:type needle: str
:rtype: int
“””
if needle == ”:
return 0
length_a = len(needle)
length_b = len(haystack)
if length_b < length_a:
return -1
for i in range(length_b):
if haystack[i] == needle[0]:
for j in range(length_a):
if i+j == length_b:
return -1
if haystack[i+j] != needle[j]:
i = -1
if j == length_a-1 and i !=-1:
return i
i = -1
return i

解题思路:这串代码其实写的有点土,还得优化下,用的就是反复循环 check,暴力破解。

正文完
 0