Leetcode 算法题08

来源:互联网 发布:网络攻防比赛题目 编辑:程序博客网 时间:2024/05/17 05:07

242. Valid Anagram

输入两个字符串,求两个字符串是否是同一个字符串打乱顺序

For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.

我的代码:Counter真的很好用

class Solution(object):    def isAnagram(self, s, t):        """        :type s: str        :type t: str        :rtype: bool        """        return collections.Counter(s)-collections.Counter(t) == collections.Counter(t)-collections.Counter(s)
大神的代码:文字不能用s.sort(),但是可以用sorted(s)

def isAnagram1(self, s, t):  #等价counter    dic1, dic2 = {}, {}    for item in s:        dic1[item] = dic1.get(item, 0) + 1    for item in t:        dic2[item] = dic2.get(item, 0) + 1    return dic1 == dic2    def isAnagram2(self, s, t):    dic1, dic2 = [0]*26, [0]*26    for item in s:        dic1[ord(item)-ord('a')] += 1    for item in t:        dic2[ord(item)-ord('a')] += 1    return dic1 == dic2    def isAnagram3(self, s, t):    return sorted(s) == sorted(t)


13. Roman to Integer

罗马数字转数字

在维基查了一下规则:

罗马数字共有7个,即Ⅰ(1)、Ⅴ(5)、Ⅹ(10)、Ⅼ(50)、Ⅽ(100)、Ⅾ(500)和Ⅿ(1000)。按照下述的规则可以表示任意正整数。需要注意的是罗马数字中没有“0”,与进位制无关。一般认为罗马数字只用来记数,而不作演算。

  • 重复数次:一个罗马数字重复几次,就表示这个数的几倍。
  • 右加左减:
    • 在较大的罗马数字的右边记上较小的罗马数字,表示大数字加小数字。
    • 在较大的罗马数字的左边记上较小的罗马数字,表示大数字减小数字。
    • 左减的数字有限制,仅限于I、X、C。比如45不可以写成VL,只能是XLV
    • 但是,左减时不可跨越一个位值。比如,99不可以用IC({\displaystyle 100-1}100-1)表示,而是用XCIX({\displaystyle [100-10]+[10-1]}[100-10]+[10-1])表示。(等同于阿拉伯数字每位数字分别表示。)
    • 左减数字必须为一位,比如8写成VIII,而非IIX。
    • 右加数字不可连续超过三位,比如14写成XIV,而非XIIII。(见下方“数码限制”一项。)
  • 加线乘千:
    • 在罗马数字的上方加上一条横线或者加上下标的Ⅿ,表示将这个数乘以1000,即是原数的1000倍。
    • 同理,如果上方有两条横线,即是原数的1000000({\displaystyle 1000^{2}}1000^{{2}})倍。
  • 数码限制:
    • 同一数码最多只能连续出现三次,如40不可表示为XXXX,而要表示为XL。
    • 例外:由于IV是古罗马神话主神朱庇特(即IVPITER,古罗马字母里没有J和U)的首字,因此有时用IIII代替IV。

我的代码:

class Solution(object):    def romanToInt(self, s):        """        :type s: str        :rtype: int        """        dic={'I':1,'V':5,'X':10,'L':50,'C':100,         'D':500,'M':1000}        ans = 0        index = 0        while index < len(s)-1:            if dic[s[index]] < dic[s[index+1]]:                ans += dic[s[index+1]] -dic[s[index]]                index += 2            else:                ans += dic[s[index]]                index += 1        if index == len(s)-1:            ans += dic[s[-1]]        return ans            
大神代码:我想得复杂了点,判断后做跳步,但是实际上直接减就可以了

class Solution:# @param {string} s# @return {integer}def romanToInt(self, s):    roman = {'M': 1000,'D': 500 ,'C': 100,'L': 50,'X': 10,'V': 5,'I': 1}    z = 0    for i in range(0, len(s) - 1):        if roman[s[i]] < roman[s[i+1]]:            z -= roman[s[i]]        else:            z += roman[s[i]]    return z + roman[s[-1]]

506. Relative Ranks

输入一个由分数组成的列表,输出相应排名列表:

Example 1:

Input: [5, 4, 3, 2, 1]Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]Explanation: The first three athletes got the top three highest scores, so they got "Gold Medal", "Silver Medal" and "Bronze Medal". 
For the left two athletes, you just need to output their relative ranks according to their scores.
class Solution(object):    def findRelativeRanks(self, nums):        """        :type nums: List[int]        :rtype: List[str]        """        ans = [0]*len(nums)        count = 1        while count <= len(nums):            index = nums.index(max(nums))            if count == 1:                ans[index] = "Gold Medal"            elif count == 2:                ans[index] = "Silver Medal"            elif count == 3:                ans[index] = "Bronze Medal"            else:                ans[index] = str(count)            nums[index] = -1            count += 1        return ans
大神的代码:先给排序后的分数按顺序排名做成词典,再用map映射原列表

def findRelativeRanks(self, nums):    sort = sorted(nums)[::-1]    rank = ["Gold Medal", "Silver Medal", "Bronze Medal"] + map(str, range(4, len(nums) + 1))    return map(dict(zip(sort, rank)).get, nums)

599. Minimum Index Sum of Two Lists

按优先级顺序给出两个人喜欢吃的餐厅名列表,求出优先级(索引)相加最小的同时喜欢的餐厅列表

Example 1:

Input:["Shogun", "Tapioca Express", "Burger King", "KFC"]["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]Output: ["Shogun"]Explanation: The only restaurant they both like is "Shogun".

Example 2:

Input:["Shogun", "Tapioca Express", "Burger King", "KFC"]["KFC", "Shogun", "Burger King"]Output: ["Shogun"]Explanation: The restaurant they both like and have the least index sum is "Shogun" with index sum 1 (0+1).
我的代码:

class Solution(object):    def findRestaurant(self, list1, list2):        """        :type list1: List[str]        :type list2: List[str]        :rtype: List[str]        """        ans = []        temp = len(list1)+len(list2)-2        for i in range(len(list1)):            if list1[i] in list2 and i+list2.index(list1[i]) < temp:                ans = [list1[i]]                temp = i+list2.index(list1[i])            elif list1[i] in list2 and i+list2.index(list1[i]) == temp:                ans.append(list1[i])        return ans

大神的代码:看起来很简洁

class Solution(object):    def findRestaurant(self, list1, list2):        """        :type list1: List[str]        :type list2: List[str]        :rtype: List[str]        """        dict1 = {rest : i for i, rest in enumerate(list1)}        dict2 = {rest : i for i, rest in enumerate(list2)}        dictSum = {rest : dict1[rest]+dict2[rest] for rest in dict1 if rest in dict2}        minSum = min(dictSum.values())        return [key for key in dictSum if dictSum[key] == minSum]

Or a little bit faster solution:

class Solution(object):    def findRestaurant(self, list1, list2):        """        :type list1: List[str]        :type list2: List[str]        :rtype: List[str]        """        dict1 = {rest : i for i, rest in enumerate(list1)}        dict2 = {rest : i for i, rest in enumerate(list2)}        dictSum = {rest : dict1[rest]+dict2.get(rest, 2017) for rest in dict1}        minSum = min(dictSum.values())        return [key for key in dictSum if dictSum[key] == minSum]

The fourth line in both solutions could be in the last one (return [key for key in dictSum if dictSum[key] == min(dictSum.values())), but that makes it slower. Is that because it calculates the min again every iteration?

217. Contains Duplicate

输入一个由数字组成的列表,判断其中是否有重复的数字

我的代码:

class Solution(object):    def containsDuplicate(self, nums):        """        :type nums: List[int]        :rtype: bool        """        dic = collections.Counter(nums)        for i in list(dic.values()):            if i > 1:                return True        return False
大神的代码:其实就是没想那么多= = 

class Solution(object):def containsDuplicate(self, nums):    """    :type nums: List[int]    :rtype: bool    """    return len(nums) != len(set(nums))



原创粉丝点击