Leetcode 算法题12

415. Add Strings

输入两个数字的字符串形式,求两数之和,要求不能直接转化

我的代码:查了一下itertools.izip_longest函数,本来想采用进位的方式,但是想到我完全不用只拘束于一位数

class Solution(object):
    def addStrings(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        list_=itertools.izip_longest(num1[::-1],num2[::-1],fillvalue='0')
        carry = 0
        nums = []
        zeros = 2*ord('0')
        for i in list_:
            nums.append((ord(i[0])+ord(i[1])-zeros))
        return str(reduce(lambda x,y:10*x+y,nums[::-1]))
大神的代码:有进位的方式和另一种和我一样但是写成一行的

def addStrings(self, num1, num2):
    z = itertools.izip_longest(num1[::-1], num2[::-1], fillvalue='0')
    res, carry, zero2 = [], 0, 2*ord('0')
    for i in z:
        cur_sum = ord(i[0]) + ord(i[1]) - zero2 + carry
        res.append(str(cur_sum % 10))
        carry = cur_sum // 10
    return ('1' if carry else '') + ''.join(res[::-1])

The above I think would be the expected answer in an interview. But just for fun based on a similar idea we can have a (rather long :-) one-liner. It technically satisfies the problem conditions, although it may warrant disqualification from the contest, depending on interpretation:

  • "You must not use any built-in BigInteger library" -> I don't use a library; I am just making use of the fact that Python's standard int supports arbitrarily large integers.
  • "or convert the inputs to integer directly" -> I don't; I sum them digit by digit. It is the result that I convert to integer and back.

Formated for added clarity, although everything can be put on the same line:

def addStrings(self, num1, num2):
     return str(
              reduce(lambda a, b: 10*a + b, 
                 map(lambda x: ord(x[0])+ord(x[1])-2*ord('0'),
                   list(itertools.izip_longest(num1[::-1], num2[::-1], fillvalue='0'))[::-1]
                 ) 
              )
            )


202. Happy Number

按如下方式判断:

Example: 19 is a happy number

  • 12 + 92 = 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1
我的代码:想到啥写啥了,应该可以更短一些

class Solution(object):
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        num = n
        list_=[]
        while num not in list_:
            list_.append(num)
            print(list_)
            temp = 0
            for s in str(num):
                temp += int(s)**2
            num = temp
        return num == 1
看到大神都用set()而非list,可能是这种情况set()更优?

def isHappy(self, n):
    mem = set()
    while n != 1:
        n = sum([int(i) ** 2 for i in str(n)])
        if n in mem:
            return False
        else:
            mem.add(n)
    else:
        return True


405. Convert a Number to Hexadecimal

32bit十进制转16进制,需要考虑负数

Example 1:

Input:
26

Output:
"1a"

Example 2:

Input:
-1

Output:
"ffffffff"
我的代码:

class Solution(object):
    def toHex(self, num):
        """
        :type num: int
        :rtype: str
        """
        if num == 0: return '0'
        if num < 0 : num = 2**32 + num
        hexa = {0:'0',1:'1',2:'2',3:'3',4:'4',5:'5',6:'6',7:'7',8:'8',
                9:'9',10:'a',11:'b',12:'c',13:'d',14:'e',15:'f'}
        ans = ''
        while num:
            s = num % 16
            ans = hexa[s] + ans
            num = num // 16
        return ans
            
大神的代码:确实用不到字典哦= =。。用的移位和按位与操作
    def toHex(self, num):
        if num==0: return '0'
        mp = '0123456789abcdef'  # like a map
        ans = ''
        for i in range(8):
            n = num & 15       # this means num & 1111b
            c = mp[n]          # get the hex char 
            ans = c + ans
            num = num >> 4
        return ans.lstrip('0')  #strip leading zeroes
还有写成一行的

class Solution(object):
    def toHex(self, num):
        return   ''.join(
                        '0123456789abcdef'[(num >> 4 * i) & 15] 
                        for i in range(8)
                        )[::-1].lstrip('0') or '0'

594. Longest Harmonious Subsequence

求一个列表中取出两个相邻数,组成最长列表的长度

Example 1:

Input: [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].
我的代码:

class Solution(object):
    def findLHS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        count = collections.Counter(nums)
        ans = 0
        for i in count:
            if count.get(i) and count.get(i-1):
                ans = max((count.get(i)+count.get(i-1)),ans)
        return ans
其他思路一样,但是更简洁,因为我当时考虑列表没有某个数时用0代替(后来发现必须跳过),改的时候保留了get函数,不用get更简洁

def findLHS(self, A):
    count = collections.Counter(A)
    ans = 0
    for x in count:
        if x+1 in count:
            ans = max(ans, count[x] + count[x+1])
    return ans

70. Climbing Stairs

给出一个阶梯的长度,一次只能走1个或2个阶梯,求有多少种不一样的走法

Example 1:

Input: 2
Output:  2
Explanation:  There are two ways to climb to the top.

1. 1 step + 1 step
2. 2 steps

Example 2:

Input: 3
Output:  3
Explanation:  There are three ways to climb to the top.

1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
我的代码:

class Solution(object):
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        def Factorial(m):
            if m == 0:return 1
            return reduce(lambda x,y:x*y,[i for i in range(m,0,-1)])
        ans = 0
        count = 0
        while count <= n//2:
            ans += Factorial(n-count)/(Factorial(count)*Factorial(n-2*count))
            count += 1
        return ans
大神的代码:什么叫看得透彻,我服

def climbStairs(self, n):
    a = b = 1
    for _ in range(n):
        a, b = b, a + b
    return a
解释为什么这个问题就是求斐波那契数列:

Base cases:
if n <= 0, then the number of ways should be zero.
if n == 1, then there is only way to climb the stair.
if n == 2, then there are two ways to climb the stairs. One solution is one step by another; the other one is two steps at one time.





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值