167. 兩數(shù)之和 II - 輸入有序數(shù)組
算法:
def twoSum(self, numbers, target):
dic = {}
r = []
for i in range(len(numbers)):
if numbers[i] in dic.keys():
r.append(dic[numbers(i)]+1)
r.append(i+1)
return r
dic[target - numbers[i]] = i
return None
分析:使用字典是最快捷的方法
168. Excel表列名稱
算法:
def convertToTitle(self, n):
r = ''
while n!=0:
r = chr((n-1)%26 + 65) + r
n = (n-1)//26
169. 求眾數(shù)
算法一:
def majorityElement(self, nums):
dic = {}
r = []
for i in range(len(nums)): #計(jì)算數(shù)字出現(xiàn)次數(shù)抚芦,存入字典
if nums[i] in dic.keys():
dic[nums[i]] += 1
else:
dic[nums[i]] = 1
times = len(nums)//2
for i in dic.keys(): #找到眾數(shù)
if dic[i] > times:
return i
算法二:
def majorityElement(self, nums):
return sorted(nums)[len(nums)//2]
分析:注意題目中存在眾數(shù)晤愧,所以直接可以將數(shù)組按大小排序遏匆,輸出中間值。
171. Excel表列序號(hào)
算法:
def titleToNumber(self, s):
r = 0
for i in range(len(s)-1,-1,-1): #將字符串倒序偏陪,i也為倒序
r += ord(s[i]-65+1) * 26**(len(s)-i-1)
return r