Leetcode 算法题10

来源:互联网 发布:图灵程序设计丛书 java 编辑:程序博客网 时间:2024/05/16 18:00

401. Binary Watch

看下图手表,输入一个数字代表LED灯亮的个数,求所有可能时间的组合

Example:

Input: n = 1
Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]
我的代码:查了一下python的组合排列函数:itertools下combinations组合,permutations排列

class Solution(object):    def readBinaryWatch(self, num):        """        :type num: int        :rtype: List[str]        """        ans = []        for i in range(min(5,num+1)):            hour_num = i            minute_num = num - hour_num            hours = map(lambda x:str(x),filter(lambda x:x<12,[sum(m) for m in itertools.combinations([1,2,4,8], hour_num)]))                        minutes = map(lambda x:str(x) if len(str(x))==2 else '0'+str(x),                         filter(lambda x:x<60,                                [sum(n) for n in itertools.combinations([1,2,4,8,16,32], minute_num)]))            print(hours,minutes)            for hour in hours:                for minute in minutes:                    combination = hour+':'+minute                     if combination not in ans:                        ans.append(combination)        return ans            
大神的代码:只能说膜拜。。。

def readBinaryWatch(self, num):    return ['%d:%02d' % (h, m)            for h in range(12) for m in range(60)            if (bin(h) + bin(m)).count('1') == num]

350. Intersection of Two Arrays II

求两个列表的交集

Example:
Given nums1 = [1, 2, 2, 1]nums2 = [2, 2], return [2, 2].

我的代码:

class Solution(object):    def intersect(self, nums1, nums2):        """        :type nums1: List[int]        :type nums2: List[int]        :rtype: List[int]        """        ans = []        a=collections.Counter(nums1)        b=collections.Counter(nums2)        ans_counter = a & b        for i,k in ans_counter.items():            ans += [i]*k        return ans    
大神的代码:

from collections import Counterclass Solution(object):    def intersect(self, nums1, nums2):        c1, c2 = Counter(nums1), Counter(nums2)        return sum([[num] * min(c1[num], c2[num]) for num in c1 & c2], [])  #sum函数后加第二个指数为[]可指定为列表的相加


268. Missing Number

给出一个1~n的列表,打乱并抽取一个数,找到这个数

我的代码:没啥难度

class Solution(object):    def missingNumber(self, nums):        """        :type nums: List[int]        :rtype: int        """        return (len(nums))*(len(nums)+1)/2 - sum(nums)

551. Student Attendance Record I

给一个字符串代表学生的出勤情况,有超过一次缺席或者连续二次以上迟到记为不及格(输出False)

  1. 'A' : Absent.
  2. 'L' : Late.
  3. 'P' : Present.

Example 1:

Input: "PPALLP"Output: True

Example 2:

Input: "PPALLL"Output: False

我的代码:

class Solution(object):    def checkRecord(self, s):        """        :type s: str        :rtype: bool        """        counter = collections.Counter(s)        return 'LLL' not in s and counter['A'] < 2  #太习惯用collections.Counter了,其实这种情况只需要使用counter('A')
大神的代码:正则表达式也是个很有用的东西

def checkRecord(self, s):    return not re.search('A.*A|LLL', s)  #正则表达式中.*代表若干任意字符(.为任意字符,*为任意数量)

or

def checkRecord(self, s):    return not (s.count('A') > 1 or 'LLL' in s)

 
504. Base 7

10进制转7进制

Example 1:

Input: 100Output: "202"

Example 2:

Input: -7Output: "-10"

我的代码:

class Solution(object):    def convertToBase7(self, num):        """        :type num: int        :rtype: str        """        if num == 0:            return '0'        rest = abs(num)        ans = ''        while rest != 0:   #等价:while rest            ans = str(rest % 7) + ans            rest = rest // 7        return ans if num > 0 else '-'+ans            
看到个用递归的思路:

Recursion will simplify the function.

def convertTo7(self, num):    if num < 0: return '-' + self.convertTo7(-num)    if num < 7: return str(num)    return self.convertTo7(num // 7) + str(num % 7)



原创粉丝点击