每日Leetcode—算法(15)

167. 两数之和 II - 输入有序数组

算法:

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. 求众数

算法一:

def majorityElement(self, nums):
    dic = {}
    r = []
    for i in range(len(nums)):      #计算数字出现次数,存入字典
        if nums[i] in dic.keys():
            dic[nums[i]] += 1
        else:
            dic[nums[i]] = 1
    times = len(nums)//2
    for i in dic.keys():          #找到众数
        if dic[i] > times:
            return i

算法二:

def majorityElement(self, nums):
    return sorted(nums)[len(nums)//2]

分析:注意题目中存在众数,所以直接可以将数组按大小排序,输出中间值。

171. Excel表列序号

算法:

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

你可能感兴趣的:(每日Leetcode—算法(15))