python在leecode刷题-第一题

发布时间:2019-05-17 22:07:04编辑:auto阅读(2084)

     

    class Solution(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int] nums=[2,7,11,15],target=9
            :type target: int
            :rtype: List[int]
            """
            hashmap={}
            for index,num in enumerate(nums):
                another_num=target-num
                if another_num in hashmap:
                    return [hashmap[another_num],index]
                hashmap[num]=index
            return None

    笔记:

    1、enumerate用法:这里其实不知道他这个循环nummerate(nums)到底能不能取出来key和value

    >>> a=[2,3]
    >>> b=enumerate(a)
    >>> b
    <enumerate object at 0x00000000031C6750>
    >>> list(b)
    [(0, 2), (1, 3)]
    >>>

    2、思想是在[2,7,11,15]里取出来第一个值,放在hashmap里,用target9减去第二个值,如果在hashmap里这个差值的存在说明满足2+7=9,然后把这个hashmap里的key-value输出来。

     

    class Solution(object):
        def reverse(self, x):
            """
            :type x: int
            :rtype: int
            """
            if x<0:
                tmp=-int(str(-x)[::-1])       
            else :
                tmp=int(str(x)[::-1])
            if tmp>=-2**31 and tmp<=2**31-1:
                return tmp
            else:
                return 0

     

     第七题

    1、[::-1]的用法,其实就是把字符串倒过来。。。就这么理解吧

    >>> x
    -123
    >>> str(x)
    '-123'
    >>> b=str(x)
    >>> b[::-1]
    '321-'
    >>> x
    -123
    >>> x=-x
    >>> x
    123
    >>> str(x)
    '123'
    >>> b=str(x)
    >>> b
    '123'
    >>> b[::-1]
    '321'
    >>>

     

      2、两个循环,第一个是求出所有数的倒序,第二个循环是满足条件范围以后 输出值,不在范围return 0

     

     

     

    总结:MLGB,传说中的leecode刷题有点东西啊,谁知道刷这东西能找到工作不,但是我想知道他是啥机制能判断出来我上传的代码对还是不对啊。

关键字

上一篇: Note of Python Turtl

下一篇: python note #1