leetcode练习笔记

leetcode 344. Reverse String

Write a function that takes a string as input and returns the string reversed.

Example:

Example:
Given s = “hello”, return “olleh”.

思路:将字符串转化为列表,利用列表的reverse()函数来求解

class Solution(object):
    def reverseString(self, s):
        """
        :type s: str
        :rtype: str
        """
        tmp=list(s)
        tmp.reverse()
        return ''.join(tmp)

leetcode345.Reverse Vowels of a String

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:

Example 1:
Given s = “hello”, return “holle”.

Example 2:

Example 2:
Given s = “leetcode”, return “leotcede”.

思路:首先先列出元音字母(注意大小写),从头扫描一遍,找出元音所在的位置,再将元音数组转至,填回原来的字符串即可

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        dic=['a','o','e','i','u','A','O','E','I','U']
        context=[]
        index=[]
        for i in range(len(s)):
            if s[i] in dic:
                context.append(s[i])
                index.append(i)
        context.reverse()
        tmp=list(s)
        for i in range(len(index)):
            tmp[index[i]]=context[i]
        return ''.join(tmp)

leetcode 22. Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:


[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

思路:DFS思想,在一对()里面要么有()要么没有,那么就可以拆分为(inner)+outter

class Solution(object):
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        dp={0:[''],1:['()']}
        def dfs(n):
            if n not in dp:
                dp[n]=[]
                for i in range(n):
                    for inner in dfs(i):
                        for outter in dfs(n-i-1):
                            dp[n].append('('+inner+')'+outter)
            return dp[n]
        return dfs(n)

leetcode 226. Invert Binary Tree

Invert a binary tree.


4
/ \
2 7
/ \ / \
1 3 6 9

to


4
/ \
7 2
/ \ / \
9 6 3 1

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def invertTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if root:  
            root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)  
        return root  

leetcode 349. Intersection of Two Arrays

Given two arrays, write a function to compute their intersection.

Example:

Example:
Given nums1 = [1, 2, 2, 1]nums2 = [2, 2], return [2].

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

思路:利用字典

class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        dictionary={}
        for i in nums1:
            if i not in dictionary:
                dictionary.setdefault(i,0)
            dictionary[i]=dictionary[i]+1
        ans=[]
        for i in nums2:
            if i in dictionary:
                ans.append(i)
                dictionary[i]=dictionary[i]-1
                if dictionary[i]==0:
                    dictionary.pop(i)
        return list(set(ans))

leetcode 350. Intersection of Two Arrays II

Given two arrays, write a function to compute their intersection.

Example:

Example:
Given nums1 = [1, 2, 2, 1]nums2 = [2, 2], return [2, 2].

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.

    Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?

  • What if nums1’s size is small compared to nums2’s size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

思路:和349类似,结果无需set

class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        dictionary={}
        for i in nums1:
            if i not in dictionary:
                dictionary.setdefault(i,0)
            dictionary[i]=dictionary[i]+1
        ans=[]
        for i in nums2:
            if i in dictionary:
                ans.append(i)
                dictionary[i]=dictionary[i]-1
                if dictionary[i]==0:
                    dictionary.pop(i)
        return ans

leetcode 29. Divide Two Integers

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

思路:不能用multiplication、division and mod operator,那么就剩下add ,sub,位操作

  1. 被除数减除数,计数加1
  2. 方法1会导致TLE,利用位运算,每次操作,让除数翻倍

注意负数符号

class Solution(object):
    def divide(self, dividend, divisor):
        """
        :type dividend: int
        :type divisor: int
        :rtype: int
        """
        ans=0
        flag=(divisor<0 and dividend>0) or (divisor>0 and dividend<0)
        a,b=abs(dividend),abs(divisor)
        while(a>=b):
            c=b
            i=0
            while(a>=c):
                a-=c
                ans+=(1<1
                c=c<<1
        if flag:
            ans=-ans
        return min(max(-2147483648, ans), 2147483647)  

你可能感兴趣的:(python,leetcode)