菜鸟刷 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__='[email protected]'

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__="[email protected]"

"""
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__="[email protected]"

"""
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

第六题 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__="[email protected]"

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__="[email protected]"

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__="[email protected]"

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

你可能感兴趣的:(菜鸟刷 Leetcode成长笔记(持续更新中))