写在前面的话好几天木有刷题啦,今天猛刷了一把,要梳理一个顺序好好的学习啦~一定要好好执行每天做题的计划!最近真的好忙碌啊,还要做视频。不过呢,看了高效学习的书,感觉其实不能说太分散的学习,应该考虑多方面的联系,形成整体性的学习,还得琢磨琢磨…小李加油呀!认真做题第一题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,暴力破解。