1. 构建乘积矩阵
class Solution:
def multiply(self , A: List[int]) -> List[int]:
# write code here
# 通过构建矩阵,分别计算下三角和上三角,并且把对应位置累乘
# 如图所示:
B = [1]*len(A)
# 下三角
for i in range(1,len(A)):
B[i] = A[i-1] * B[i-1]
temp = 1
# 上三角
for i in range(len(A)-2, -1, -1):
temp = A[i+1] * temp
B[i] = B[i] * temp
return B
# 暴力破解法
B = []
for i in range(len(A)):
temp = 1
for s in range(len(A)):
if s != i:
temp = temp*A[s]
B.append(temp)
return B
2.第一个只出现一次的字符
class Solution:
def FirstNotRepeatingChar(self , str: str) -> int:
# write code here
# 使用python自带的count函数:
for s in str:
if str.count("%s"%(s))==1:
return str.index("%s"%(s))
break
return -1
# 简单的方法,直接使用字典来存储每个字符出现的总次数、以及该字符第一次出现的位置
num_dict = {}
str_list = list(str)
for i in range(len(str_list)):
if str_list[i] not in num_dict.keys():
num_dict[str_list[i]]=[1,i]
continue
else:
num_dict[str_list[i]][0] += 1
for k,v in num_dict.items():
if v[0] == 1:
return v[1]
else:
continue
return -1
3.替换空格
class Solution:
def replaceSpace(self , s: str) -> str:
# write code here
# 遍历,依次替换
res = ""
for si in list(s):
if si == " ":
res += "%20"
else:
res += si
return res
# 使用python自带replace函数
s = s.replace(" ", "%20")
return s
4.数组中出现次数超过一半的数字
class Solution:
def MoreThanHalfNum_Solution(self , numbers: List[int]) -> int:
# write code here
# 排序后,直接取最中间的元素。因为过半的话,即使排在最前面或最后面,都一定可以分布到正中间
numbers = sorted(numbers)
return numbers[len(numbers)//2]
# 首先排序,然后遍历数组依次把每个元素当成答案
numbers = sorted(numbers)
res = numbers[0]
count = 0
lenth = len(numbers)
for num in numbers:
if count > lenth/2:
return res
if num == res:
count += 1
continue
else:
res = num
count = 1
return res