Leetcode题解集

1. Two Sum

  1. if there are chinese characters in comment, you have to add #coding:utf-8 in front of the .py file, or there would be a problem.
  2. the enumerate() function to get the index and value in a array at the same time
  3. for each element, record the value need and the corresponding index

Sample Input 1:

nums = [2, 7, 11, 15], target = 9

Sample Output 1:

[0, 1]

Code

#coding:utf-8
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        enumerate()函数的功能
        """
        # record the number need and the position who need it
        dic={}
        for i,num in enumerate(nums):
            if num in dic:
                return [dic[num], i]
            else:
                dic[target-num]=i

s=Solution()
print(s.twoSum([2, 7, 11, 15],9))

2. Add Two Numbers

  1. robustness the input array is not nullptr and return nullptr if the two ptr are all nullptr, but it’s not requested in this problem
  2. only when the l1 or l2 is true, fill the next ListNode

Sample Input 1:

(2 -> 4 -> 3) + (5 -> 6 -> 4)

Sample Output 1:

7 -> 0 -> 8

Code

# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if l1 is None:
            return l2
        if l2 is None:
            return l1
        ans=ListNode(0)
        tmp=ans
        carry=0
        while(l1 or l2):
            temp=0
            if l1:
                temp+=l1.val
                l1=l1.next
            if l2:
                temp += l2.val
                l2=l2.next
            temp+=carry
            carry=temp//10
            temp=temp%10
            nxt=ListNode(0)
            tmp.next=ListNode(temp)
            tmp=tmp.next
        if carry == 1:
            tmp.next=ListNode(1)
        del tmp
        return ans.next

3. Longest Substring Without Repeating Characters

  1. there must be two-level nested loop, when the repeating element occurs, break inter-loop and add one in outer-loop
  2. only in this way, you can consider all the situations

Sample Input 1:

“abcabcbb”

Sample Output 1:

3

Sample Input 2:

“bbbbb”

Sample Output 2:

1

Sample Input 3:

“pwwkew”

Sample Output 3:

3

Code

#coding:utf-8

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        s1=set()
        num=0
        maxnum=0
        for i in range(len(s)):
            s1.clear()
            num=0
            for j in s[i:]:
                if j not in s1:
                    num+=1
                    s1.add(j)
                else:
                    break
            if num>maxnum:
                maxnum=num
        return maxnum

s=Solution()
print(s.lengthOfLongestSubstring("abcabcbb"))

4. Median of Two Sorted Arrays

  1. if you want to type simple code, merge the two array and sort it, but the time complexity is large.
  2. here I exchange space complexity with time complexity.

Sample Input 1:

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

Sample Output 1:

2

Sample Input 2:

nums1 = [1, 2]
nums2 = [3, 4]

Sample Output 2:

2.5

Code

class Solution:
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        len1,len2=len(nums1),len(nums2)
        l=len1+len2
        n=l//2
        res=[]
        flag=0
        while nums1 and nums2 and flag <= n:
            if nums1[0]<nums2[0]:
                res.append(nums1.pop(0))
            else:
                res.append(nums2.pop(0))
            flag+=1
        while len(res)<n+1:
            res.append(nums1.pop(0) if nums1 else nums2.pop(0))
        return res[n] if l%2==1 else (res[n]+res[n-1])/2

s=Solution()
print(s.findMedianSortedArrays([1,2],[3,4]))

5. Longest Palindromic Substring

  1. the idea is loop each character in s and center-expend it until the border or not suitable — s[l]!=s[r]

Sample Input 1:

“babad”

Sample Output 1:

“bab”

Sample Input 2:

“cbbd”

Sample Output 2:

“bb”

Code

#coding:utf-8
# 中心拓展法求最大回文子串
class Solution:
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        start=end=0
        for i in range(len(s)):
            len1=self.expend(s,i,i)
            len2=self.expend(s,i,i+1)
            maxlen=max(len1,len2)
            if maxlen>end-start+1:
                start=i-(maxlen-1)//2
                end=i+maxlen//2
        return s[start:end+1]

    def expend(self,s,l,r):
        # for the last time, the l is subtract one and r add one, but the current l and r are not suitable,
        # so you have to return the r-l-1.
        while l>=0 and r<len(s) and s[l]==s[r]:
            l-=1
            r+=1
        return r-l-1
s=Solution()
print(s.longestPalindrome("babad"))

6. Zigzag Conversion

  1. the main idea is insert each row array using step, so you have to check whether the numRows is one

Sample Input 1:

s = “PAYPALISHIRING”, numRows = 3

Sample Output 1:

“PAHNAPLSIIGYIR”

Sample Input 2:

s = “PAYPALISHIRING”, numRows = 4

Sample Output 2:

“PINALSIGYAHRPI”

Code

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

7. Reverse Integer

  1. the input is int type, but you have to check whether the output is also int

Sample Input 1:

123

Sample Output 1:

321

Sample Input 2:

-123

Sample Output 2:

-321

Sample Input 3:

120

Sample Output 3:

21

Code

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        minus=False
        if x<0:
            minus=True
            x=-x
        ans=0
        while x:
            ans=ans*10+x%10
            x//=10
        if minus:
            ans=-ans
        if ans > 2147483647 or ans < -2147483648:
            return 0
        return ans

s=Solution()
print(s.reverse(1534236469))

8. String to Integer (atoi)

  1. first to check whether the str is null
  2. then to check the symbolic bit, if there is a symbolic bit, record it and to check whether the remaining is null
  3. if the remaining string is not null, to check whether the remaining is a number
  4. finally, check whether the ans is in range int

Sample Input 1:

“42”

Sample Output 1:

42

Sample Input 2:

" -42"

Sample Output 2:

-42

Sample Input 3:

“4193 with words”

Sample Output 3:

4193

Sample Input 4:

“words and 987”

Sample Output 4:

0

Sample Input 5:

“-91283472332”

Sample Output 5:

-2147483648

Code

class Solution:
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        str=str.strip()
        if str=='':
            return 0
        flag=''
        i = 0
        if str[0]=='+' or str[0]=='-':
            flag='-' if str[0]=='-' else ''
            i+=1
            if str[1:]=='':
                return 0
        ans=0
        if str[i] < '0' or str[i] > '9':
            # print("取出第一個符號後爲空")
            return 0
        while i<len(str) and str[i]>='0' and str[i]<='9':
            ans=ans*10+int(str[i])
            i+=1
        if flag=='-':
            ans=-ans
        if ans>2147483647:
            return 2147483647
        if ans<-2147483648:
            return -2147483648
        return ans

s=Solution()
print(s.myAtoi("1"))

9. Palindrome Number

  1. if the input is less than zero, return False directly

Sample Input 1:

121

Sample Output 1:

True

Sample Input 2:

-121

Sample Output 2:

False

Sample Input 3:

10

Sample Output 3:

True

Code

class Solution:
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x<0:
            return False
        origin=x
        ans=0
        while x:
            ans=ans*10+x%10
            x//=10
        return ans==origin

s=Solution()
print(s.isPalindrome(10))

10. Regular Expression Matching

  1. here, the regular rule is a difficult problem

Sample Input 1:

s = “aa”
p = “a”

Sample Output 1:

false

Sample Input 2:

s = “aa”
p = “a*”

Sample Output 2:

true

Sample Input 3:

s = “ab”
p = “.*”

Sample Output 3:

true

Sample Input 4:

s = “aab”
p = “cab”

Sample Output 4:

true

Sample Input 5:

s = “mississippi”
p = “misisp*.”

Sample Output 5:

false

Code

class Solution:
    def isMatch(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: bool
        """
        dp = [[False for _ in range(len(p) + 1)] for _ in range(len(s) + 1)]
        dp[0][0] = True
        for j in range(2,len(p) + 1):# start from the second element to the last element
            if p[j - 1] == '*':
                dp[0][j] = dp[0][j - 2]
        for i in range(1,len(s) + 1):
            for j in range(1,len(p) + 1):
                if p[j - 1] == '*':
                    dp[i][j] = dp[i][j-1] or dp[i][j-2] or (dp[i-1][j] and (s[i-1] == p[j-2] or p[j-2] == '.'))
                elif p[j-1] == '.' or s[i-1] == p[j - 1]:
                    dp[i][j] = dp[i-1][j-1]

        return dp[len(s)][len(p)]
s = Solution()
print(s.isMatch("", ".b*"))

53

  1. enumerate(nums): extract the index and value from array
  2. when the currentSum is less than or equals zero, it would be meaningless for the situation when maxSum is more than zero
  3. when the maxSum is less than zero, traverse all the situations

Sample Input 1:

[-2,1,-3,4,-1,2,1,-5,4]

Sample Output 1:

6

Code

class Solution:
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        maxSum=nums[0]
        for idx, val in enumerate(nums):
            tempNums=nums[idx:]
            currentSum=0
            for i in tempNums:
                currentSum+=i
                if maxSum>0 and currentSum<=0:
                    idx+=i
                    break
                if currentSum>maxSum:
                    maxSum=currentSum
        return maxSum

s=Solution()
print(s.maxSubArray([-2,-1]))

58

  1. last word means the last non-space word, so s=s.strip() to delete the space of beginning and end
  2. when the current character is ' ', recount the word

Sample Input 1:

“Hello World”

Sample Output 1:

5

Code

class Solution:
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        s=s.strip()
        cur_len=0
        for i in s:
            if i==" ":
                cur_len=0
            else:
                cur_len+=1
        return cur_len

s=Solution()
print(s.lengthOfLastWord("Hello World"))

66

  1. len(l): return the length of list
  2. l.insert(0,5): insert 5 to the position of index 0 on the list, the position is represented by a number

Sample Input 1:

[1,2,3]

Sample Output 1:

[1,2,4]

Sample Input 2:

[4,3,2,1]

Sample Output 2:

[4,3,2,2]

Code

class Solution:
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        carry=0
        len1=len(digits)
        for i in range(len1):
            temp=digits[len1-i-1]+carry
            if i==0:
                temp+=1
            carry=temp//10
            temp%=10
            digits[len1 - i - 1]=temp
        if carry==1:
            # here the iterator is not necessary
            digits.insert(0,1)
        return digits
s=Solution()

print(s.plusOne([9,9]))

67

  1. reverse the list: l[::-1]

Sample Input 1:

a = “11”, b = “1”

Sample Output 1:

“100”

Sample Input 2:

a = “1010”, b = “1011”

Sample Output 2:

“10101”

Code

class Solution:
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        a=a[::-1]
        b=b[::-1]
        l1=len(a)
        l2=len(b)
        l=min(l1,l2)
        s=''
        if l1==l:
            a+='0'*(l2-l)
        else:
            b+='0'*(l1-l)
        l=len(a)
        carry=0
        for i in range(l):
            temp=int(a[i])+int(b[i])+carry
            carry=temp//2
            temp%=2
            s+=str(temp)
        if carry==1:
            s+='1'
        return s[::-1]

s=Solution()
print(s.addBinary("1","111"))

69

  1. the time complexity must be logn, the n won’t be accepted

Sample Input 1:

4

Sample Output 1:

2

Sample Input 1:

8

Sample Output 1:

2

Code

class Solution:
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        start=1
        end=x
        mid=(start+end)//2
        while end-start!=1:
            if mid*mid==x:
                return mid
            if mid*mid<x:
                start=mid
            if mid*mid>x:
                end=mid
            mid=(start+end)//2
        return mid
s=Solution()
print(s.mySqrt(4))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值