27、移除元素
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
i=len(nums)-1
while i>=0:
if nums[i]==val:
nums.pop(i)
i-=1
return len(nums)
总结:
1、通过倒序索引避免删除元素时索引错位,最后返回处理后列表的新长度。
2、时间复杂度O(n)。
28、找出字符串中第一个匹配项的下标
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
return haystack.find(needle)
35、搜索插入位置
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target not in nums:
nums.append(target)
nums.sort()
return nums.index(target)
else:
return nums.index(target)
58、最后一个单词的长度
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
s=s.strip(' ')
slst=s.split(' ')
return len(slst[len(slst)-1])