菜鸟刷 Leetcode成长笔记(持续更新中)

图片发自简书App

第一题 TwoSum

如果对Python中的数据结构学习比较扎实的同学来说,python几行代码就可以搞定这道题的。读完代码你可以清楚我的实现过程。
题目要求如下:


TwoSum.JPG

如果有同学可以写出更简单的代码,可以分享出来,谢谢来阅!

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: list[int]
        """
        for x in range(len(nums)):
            complement = target - nums[x]
            # 利用列表解析式才筛选出符合条件元素角标
            complement_lookup = ([index for index, num in enumerate(nums) if (num == complement and index != x)]) 
            print(complement_lookup)
            if complement_lookup == []:
                continue
            else:
                return [x,complement_lookup[0]]
s=Solution()
print s.twoSum([2,6,4,9,0,7],9)

下面的代码是测试时写的。提交时就不用Print出结果的

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: tuple[int]
        """
        for x in range(len(nums)):
            complement = target - nums[x]
            complement_lookup = ([index for index, num in enumerate(nums) if (num == complement and index != x)])
            if complement_lookup == []:
                continue
            else:
                print (x,complement_lookup[0])
s=Solution()
print s.twoSum([2,6,4,9,0,7],9)

第二题 AddTwoNumbers

本体考察的是链表的操作,在python中实现链表的操作,首先得需要自定义一个表示链表中节点的类。
题目要求:


addTwoNumber.JPG
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__='byx54192@gmail.com'

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        result = []
        curr = None
        carry = 0
        while l1 is not None and l2 is not None:
            carry, result = self._addnumbers(l1.val, l2.val, carry, result)
            l1 = l1.next
            l2 = l2.next
        
        while l1 is not None:
            carry, result = self._addnumbers(l1.val, 0, carry, result)
            l1 = l1.next
        
        while l2 is not None:
            carry, result = self._addnumbers(0, l2.val, carry, result)
            l2 = l2.next   
        return result
        
    def _addnumbers(self, val1, val2, carry, result):
        curr = ListNode((val1 + val2 + carry) % 10 )
        carry = (val1 + val2 + carry) / 10
        result.append(curr.val)
        return carry, result
class ListNode:
    def __init__(self,val,next=None):
        self.val=val
        self.next=next

本地调试代码如下:
需要把链表链接起来。

lis=[]
s=Solution()

p=ListNode(2)
p2=ListNode(4)
p3=ListNode(3)
p.next=p2
p2.next=p3
#p3.next=None

w=ListNode(5)
w2=ListNode(6)
w3=ListNode(4)
w.next=w2
w2.next=w3
#w3.next=None
lis.append(s.addTwoNumbers(p,w))

print(lis)

第三题 lengthOfLongestSubstring

longestSubstring.JPG
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
"""

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        longestlenth = 1
        substr=""
        for item in s:
            if item not in substr:
                substr+=item
                print("1-"+substr)
            else:
                if len(substr)>longestlenth:
                    print('2-'+substr)
                    longestlenth=len(substr)
                substr+=item
                substr=substr[substr.index(item)+1:]
                print('3-'+substr)
        if len(substr)>longestlenth:
            longestlenth=len(substr)
        return longestlenth
sub=Solution()
s='pwwwkew'
print(sub.lengthOfLongestSubstring(s))

第四题 Median of Two Sorted Arrays

Median of Two Sorted Arrays.JPG
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__="byx54192@gmail.com"

"""
There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

Example 1:
nums1 = [1, 3]
nums2 = [2]

The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5
"""

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        num=sorted(num1+num2)
        if len(num)%2==0:
            return float(num[int(len(num)/2)-1]+num[int(len(num)/2)])/2
        else:
            return float(num[int((len(num)+1)/2)-1])

第五题 LongestPalindrome

longestPalindrome.JPG
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__="byx54192@gmail.com"

"""
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example:
Input: "cbbd"
Output: "bb"
"""
class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        if len(s)==0 or len(s)==1:
            return s
        sub=s[0:1]
        for i in range(len(s)-1):
            s1=self.isPalindrome(s,i,i)
            if len(s1)>len(sub):
                sub=s1
            s2=self.isPalindrome(s,i,i+1)
            if len(s2)>len(sub):
                sub=s2
        return sub
    def isPalindrome(self,s,x,y):
        while x>=0 and y<len(s) and s[x]==s[y]:
            x-=1
            y+=1
        return s[x+1:y]

第六题 ZigZag Conversion

Zig.JPG

在解这道题时,关键在于理解zigzag的写入方式,我起初想通过计算每个字符的角标去解决这个问题,发现很麻烦,而且解决这种问题时,不应该增加复杂度。所以我们就按照最简单的写入逻辑去解决这种问题。


zigzag.JPG

如果你理解了上面图片中的示例,剩下的无非就是填充的列在递增或者递减而以,最终返回结果必须是一个字符串。

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows == 1:
            return s
        zigzag = ['' for i in range(numRows)] 
        row = 0                                
        step = 1                              
        for c in s:
            if row == 0:
                step = 1
            if row == numRows - 1:
                step = -1
            zigzag[row] += c
            row += step
        return ''.join(zigzag)

第七题 Reverse Integer

题目要求:


reverse intege.JPG

需要注意的是32位整数的范围:最大的32位整数是2^31=2147483647

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__="byx54192@gmail.com"

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x<0:
            x=abs(x)
            restr=[x for x in str(x)]
            restr.reverse()
            renum=int(''.join(restr))
            return 0-self.judge(renum)
        if x>=0:
            restr=[x for x in str(x)]
            restr.reverse()
            renum=int(''.join(restr))
            return self.judge(renum)
    def judge(self,renum):
        if renum > 2**31:
            return 0
        else:
            return renum


第八题 String to Integer (atoi)

下面是用两种方法解题:

题目翻译

实现“atoi”函数,将字符串转换成整数。
提示:请仔细考虑所有可能的输入情况。

思路方法

通过试错可以总结出要注意的四个点:

  1. 输入字符串为空、或其他不合法情况,返回0;
  2. 字符串开头的空格要在预处理中删掉;
  3. 处理可能出现的正负号“+”,“-”,正负号只能出现一次;
  4. 超出整数范围的值取整数范围的边界值。
思路一

按照上面要注意的点,比较可读的解法如下。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__="byx54192@gmail.com"

class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        if not str:
            return 0
        str = str.strip()
        print(str)
        number, flag = 0, 1
        if str[0] == '-':
            str = str[1:]
            flag = -1
        elif str[0] == '+':
            str = str[1:]
        for c in str:
            if c >= '0' and c <= '9':
                number = 10*number + ord(c) - ord('0')
            else:
                break
        number = flag * number
        number = number if number <= 2147483647 else 2147483647
        number = number if number >= -2147483648 else -2147483648
        return number
思路二

利用正则表达式解决问题

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__="byx54192@gmail.com"

class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        str = str.strip()
        try:
            import re 
            res = re.search('(^[\+\-]?\d+)', str).group()
            res = int(res)
            res = res if res <= 2147483647 else 2147483647
            res = res if res >= -2147483648 else -2147483648
        except:
            res = 0
        return res

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,036评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,046评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,411评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,622评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,661评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,521评论 1 304
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,288评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,200评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,644评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,837评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,953评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,673评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,281评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,889评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,011评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,119评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,901评论 2 355

推荐阅读更多精彩内容