刷题

 

Index of item

Leetcode:

104. 二叉树的最大深度

107. 二叉树的层次遍历 II

108. 将有序数组转换为二叉搜索树

110. 平衡二叉树

111. 二叉树的最小深度

112.路径总和

118.杨辉三角

119.杨辉三角Ⅱ

121.买卖股票的最佳时机

122.买卖股票的最佳时机

125.验证回文串

136.只出现一次的数字

141.环形链表

155.最小栈

160.相交链表

167.两数之和Ⅱ-输入有序数组

168.excel表列名称

169.求众数

171.Excel表列序号

172.阶乘后的零

189.旋转数组

190.颠倒二进制位

191.位1 的个数

198.打家劫舍

202.快乐数

203.移除链表元素

204.计数质数

205.同构字符串

206.反转链表

217.存在重复元素

217.存在重复元素Ⅱ

225.用队列实现栈


一、线性表

1、数组

面试题3:二维数组中的查找 

面试题14:调整数组顺序使得奇数位于偶数前面

面试题29:数组中出现超过一半的数字

面试题30:最小的k个数

面试题33:把数组排成最小的数

面试题36:数组中的逆序对

面试题40:数字在排序数组中出现的次数

面试题51:数组中重复的数字

面试题52:构建乘积数组

2、链

面试题5:从尾到头打印链表

面试题13:在O(1)时间删除链表结点

面试题15:链表中倒数第k个结点

面试题16:反转链表

面试题17:合并两个排序的链表

面试题26:复杂链表的复制

面试题37:两个链表的第一个公共结点

面试题56:链表中环的入口结点

面试题57:删除链表中重复的结点

二、字符串

面试题4:替换空格

面试题12:打印1到最大的n位数

面试题28:字符串的排列

面试题32:从1到n整数中1出现的次数

面试题35:第一个只出现1次的字符

面试题42:反转单词顺序以及左旋转字符串

面试题49:把字符串转换成整数

面试题53:正则表达式匹配

面试题54:表示数值的字符串

面试题55:字符流中第一个不重复的字符

三、栈和队列

面试题7:用两个栈实现队列&用两个队列实现栈

面试题21:包含min函数的栈

面试题22:栈的压入、弹出序列

面试题65:滑动窗口的最大值

四、树

面试题6:重建二叉树

面试题18:树的子结构

面试题19:二叉树镜像

面试题23:从上往下打印二叉树

面试题24:二叉搜索树的后序遍历

面试题25:二叉树中和为某一值的路径

面试题27:二叉搜索树与双向链表

面试题39:二叉树的深度

面试题50:树中两个节点的最低公共祖先

面试题58:二叉树的下一个节点

面试题59:对称的二叉树

面试题60:把二叉树打印成多行

面试题61:按之字形顺序打印二叉树

面试题62:序列化二叉树

面试题63:二叉搜索树的第k个结点

牛客剑指题:平衡二叉树

五、查找和排序

面试题8:旋转数组中的最小数字

六、动态规划

面试题9:斐波那契数列

面试题31:连续子数组的最大和

面试题34:丑数

面试题45:圆圈中最后剩下的数字

七、回朔法

面试题66:矩阵中的路径

面试题67:机器人的运动范围

八、细节实现题

面试题10:二进制中1的个数

面试题11:数值的整数次方

面试题20:顺时针打印矩阵

面试题41:和为s的两个数字VS和为s的连续正数序列

面试题43:n哥骰子的点数

面试题44:扑克牌顺子

面试题46:求1+2+3+.......+n

面试题47:不用加减乘除做加法

面试题64:数据流中的中位数


 

一、线性表

1、数组

面试题3:二维数组中的查找 

题目描述:在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

# -*- coding:utf-8 -*-
class Solution:
    # array 二维列表
    def Find(self, target, array):
        raws = len(array)-1
        clos = len(array[0])-1
        j = 0
        i = raws
        while j <= clos and i >= 0:
            if(target < array[i][j]):
                i -= 1
            elif(target > array[i][j]):
                j += 1
            else:
                return True
        return False
 

面试题14:调整数组顺序使得奇数位于偶数前面

题目描述:输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。

# -*- coding:utf-8 -*-
class Solution:
    def reOrderArray(self, array):
        size = len(array)
        a = []
        for i in range(size):
            if int(array[i]) % 2 == 1:
                a.append(array[i])
        for m in range(size):
            if int(array[m]) %2 == 0:
                a.append(array[m])
        return a
# -*- coding:utf-8 -*-
from collections import deque
class Solution:
    def reOrderArray(self, array):
        size = len(array)
        a = deque()
        for i in range(size):
            if int(array[size - i - 1]) % 2 == 1:
                a.appendleft(array[size - i - 1])
            if int(array[i]) % 2 == 0:
                a.append(array[i])
        return list(a)

面试题29:数组中出现超过一半的数字

题目描述:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。

def Morethanhalfnum(nums):
    l1 = len(nums)
    if l1 <= 1:
        return nums
    a, b = nums[0], 1
    for i in range(1, l1):
        if a == nums[i]:
            b += 1
        elif b == 0:
            a = nums[i]
            b += 1
        else:
            b -= 1
    count = 0
    for j in range(l1):
        if nums[j] == a:
            count += 1
    if count>l1/2:
        return a
    else:
        return 0

print(Morethanhalfnum([1,2,3,2,2,2,5,4,2]))

面试题30:最小的k个数

题目描述:输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

# -*- coding:utf-8 -*-
class Solution:
    def GetLeastNumbers_Solution(self, arr, k):
        if len(arr) == 0:
            return []
        n = len(arr)
        if n < k:
            return []
        arr = sorted(arr)
        return arr[:k]

面试题33:把数组排成最小的数

题目描述:输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。

思路:用快速排序思想

# -*- coding:utf-8 -*-
class Solution:
    def sor_list(self, numbers):
        if len(numbers) <=1:
            return numbers
        left = self.sor_list([i for i in numbers[1:] if str(i)+str(numbers[0]) < str(numbers[0])+str(i)])
        right = self.sor_list([i for i in numbers[1:] if str(i)+str(numbers[0]) >= str(numbers[0])+str(i)])
        return left+[numbers[0]]+right
    def PrintMinNumber(self, numbers):
        sor_list = self.sor_list(numbers)
        res = ''
        for i in range(len(sor_list)):
            res = res +str(sor_list[i])
        return res

面试题36:数组中的逆序对

题目描述:在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007

输入描述:题目保证输入的数组中没有的相同的数字

数据范围:对于%50的数据,size<=10^4;对于%75的数据,size<=10^5;对于%100的数据,size<=2*10^5

示例1:输入:1,2,3,4,5,6,7,0。输出:7

思路:归并排序

看到题目第一个时间想一个一个比较,但是时间复杂度达到O(n2)。看了网上答案,用归并排序还是过不去。。。

自己写的过不去的code:

# -*- coding:utf-8 -*-
class Solution:
    def InversePairs(self, data):
        # write code here
        if not data:
            return 0
        tmp = [i for i in data]
        return self.merge_sort(tmp, data, 0, len(data)-1)%1000000007
    
    def merge_sort(self, tmp, data, start, end):
        if start >= end:
            tmp[start] = data[start]
            return 0
        mid = (start+end)/2
        left = self.merge_sort(data, tmp, start, mid)
        right = self.merge_sort(data, tmp, mid+1, end)
        
        i = start
        j = mid+1
        index = start
        count = 0
        while i <= mid and j <= end:
            if data[i] <= data[j]:
                tmp[index] = data[i]
                i += 1
            else:
                count += mid-i+1
                tmp[index] = data[j]
                j += 1
            index += 1
        while i <= mid:
            tmp[index] = data[i]
            i += 1
            index += 1
        while j <= end:
            tmp[index] = data[j]
            j += 1
            index += 1
        return count + left + right

 

面试题40:数字在排序数组中出现的次数

题目描述:统计一个数字在排序数组中出现的次数。

# -*- coding:utf-8 -*-
class Solution:
    def GetNumberOfK(self, data, k):
        num = 0
        for i in range(len(data)):
            if data[i] == k:
                num += 1
        return num
# -*- coding:utf-8 -*-
class Solution:
    def GetNumberOfK(self, data, k):
        # write code here
        return data.count(k)

面试题51:数组中重复的数字

题目描述:在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。

# -*- coding:utf-8 -*-
class Solution:
    # 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
    # 函数返回True/False
    def duplicate(self, numbers, duplication):
        # write code here
        if numbers == None or numbers == []:
            return False
        #边界条件
        s  = []
        for i in numbers:
            if i in s:
                duplication[0] = i
                return True
            s.append(i)
        return False
# -*- coding:utf-8 -*-
import collections
class Solution:
    # 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
    # 函数返回True/False
    def duplicate(self, numbers, duplication):
        # write code here
        flag=False
        c=collections.Counter(numbers)
        for k,v in c.items():
            if v>1:
                duplication[0]=k
                flag=True
                break
        return flag

面试题52:构建乘积数组

题目描述:给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1],其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。不能使用除法。

# -*- coding:utf-8 -*-
class Solution:
    def multiply(self, A):
        x = 1
        if len(A) <= 1:
            return A
        B = []
        for i in range(len(A)):
            for j in range(len(A)):
                if j != i:
                    x *= A[j]
            B.append(x)
            x = 1
        return B
# -*- coding:utf-8 -*-
class Solution:
    def multiply(self, A):
        # write code here
        if not A:
            return []
        # 计算前面一部分
        num = len(A)
        B = [None] * num
        B[0] = 1
        for i in range(1, num):
            B[i] = B[i-1] * A[i-1]
        # 计算后面一部分
        # 自下而上
        # 保留上次的计算结果乘本轮新的数,因为只是后半部分进行累加,所以设置一个tmp,能够保留上次结果
        tmp = 1
        for i in range(num-2, -1, -1):
            tmp *= A[i+1]   
            B[i] *= tmp
        return B

2、链

面试题5:从尾到头打印链表

题目描述

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # 返回从尾部到头部的列表值序列,例如[1,2,3]
    def printListFromTailToHead(self, listNode):
        arr = []
        cur = listNode
        while cur:
            arr.append(cur.val)
            cur = cur.next
        arr.reverse()
        return arr

面试题13:在O(1)时间删除链表结点

面试题15:链表中倒数第k个结点

题目描述:输入一个链表,输出该链表中倒数第k个结点。  (快慢指针,遍历一遍即可)

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def FindKthToTail(self, head, k):
        # write code here
        pre = post = head
        # 快指针先走k步
        for i in range(k):
            # 如果k大于链表长度,返回空
            if pre == None:
                return None
            pre = pre.next
        # 快慢指针同时往前走
        while pre != None:
            pre = pre.next
            post = post.next
        return post

面试题16:反转链表

题目描述:输入一个链表,反转链表后,输出新链表的表头。

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        if pHead is None:
            return pHead
        rev = None
        while pHead:
            tmp = pHead.next
            pHead.next = rev
            rev = pHead
            pHead = tmp
        return rev

面试题17:合并两个排序的链表

题目描述:输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

# -*- coding:utf-8 -*-
#class ListNode:
#    def __init__(self, x):
#        self.val = x
#        self.next = None
class Solution:
    # 返回合并后列表
    def Merge(self, pHead1, pHead2):
        res = ListNode(90)
        p = res
        while pHead1 and pHead2:
            if pHead1.val < pHead2.val:
                res.next = pHead1
                pHead1 = pHead1.next
            else:
                res.next = pHead2
                pHead2 = pHead2.next
            res = res.next
        if pHead1:
            res.next = pHead1
        if pHead2:
            res.next = pHead2
        return p.next
class Solution:
    # 返回合并后列表
    def Merge(self, pHead1, pHead2):
        # write code here
        if pHead1 == None:
            return pHead2
        if pHead2 == None:
            return pHead1
        pMergedHead = None
        if pHead1.val < pHead2.val:
            pMergedHead = pHead1
            pMergedHead.next = self.Merge(pHead1.next, pHead2)
        else:
            pMergedHead = pHead2
            pMergedHead.next = self.Merge(pHead1, pHead2.next)
        return pMergedHead

面试题26:复杂链表的复制

题目描述:输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

 

面试题37:两个链表的第一个公共结点

题目描述:输入两个链表,找出它们的第一个公共结点。

思路:用利用两个链表的长度差

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def lenListNode(self, pHead):
        l = 0
        while pHead:
            pHead = pHead.next
            l += 1
        return l
    def FindFirstCommonNode(self, pHead1, pHead2):
        l1 = self.lenListNode(pHead1)
        l2 = self.lenListNode(pHead2)
        if l1 < l2:
            l1, l2 = l2, l1
            pHead1, pHead2 = pHead2, pHead1
        while l1-l2:
            pHead1 = pHead1.next
            l1 -= 1
        while pHead1 != pHead2:
            pHead1 = pHead1.next
            pHead2 = pHead2.next
        return pHead1

网上很好的思路:https://blog.csdn.net/Lynette_bb/article/details/75674765 优秀

第一种情况:相同长度有交点
两个指针一起走,步长一致,碰到第一个相同的节点 p1 == p1,退出循环,return p1。
第二种情况:相同长度无交点
两个指针一起走,直到走到最后一个节点,p1.next 和 p2.next都为 None,满足 相等的条件,退出循环,return p1。
第三种情况:不同长度有交点
两个指针一起走,当一个指针p1走到终点时,说明p1所在的链表比较短,让p1指向另一个链表的头结点开始走,直到p2走到终点,让p2指向短的链表的头结点,那么,接下来两个指针要走的长度就一样了,变成第一种情况。
第四种情况:不同长度无交点
两个指针一起走,当一个指针p1走到终点时,说明p1所在的链表比较短,让p1指向另一个链表的头结点开始走,直到p2走到终点,让p2指向短的链表的头结点,那么,接下来两个指针要走的长度就一样了,变成第二种情况。

# -*- coding:utf-8 -*-
'''
两个链表的第一个公共节点
题目描述
输入两个链表,找出它们的第一个公共结点。
'''
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        # write code here
        if not pHead1 or not pHead2:
            return None
        p1, p2 = pHead1, pHead2
        while p1 != p2:
            p1 = pHead2 if not p1 else p1.next
            p2 = pHead1 if not p2 else p2.next
        return p1

面试题56:链表中环的入口结点

题目描述:给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。

思想:第一步,用两个快慢指针找环中相汇点。分别用slow, fast指向链表头部,slow每次走一步,fast每次走二步,直到fast == slow找到在环中的相汇点。
           第二步,找环的入口。当fast == slow时,假设slow走过x个节点,则fast走过2x个节点。设环中有n个节点,因为fastslow多走一圈(n个节点),所以有等式2x = n + x,可以推出n = x,即slow实际上走了一个环的步数。这时,我们让fast重新指向链表头部pHeadslow的位置不变,然后slowfast一起向前每次走一步,直到fast == slow,此时两个指针相遇的节点就是环的入口。

    # -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def EntryNodeOfLoop(self, pHead):
        pFast = pHead
        pSlow = pHead
        while pFast != None and pFast.next != None:
            pFast = pFast.next.next
            pSlow = pSlow.next
            if pFast == pSlow:
                break
        if pFast == None or  pFast.next == None:
            return None
        pFast = pHead
        while (pFast != pSlow):
            pFast = pFast.next
            pSlow = pSlow.next
        return pFast
        # write code here

面试题57:删除链表中重复的结点

题目描述:在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def deleteDuplication(self, pHead):
        first = ListNode(-1)
        first.next = pHead    #添加一个头节点
        last = first
        while pHead and pHead.next:
            if pHead.val == pHead.next.val:
                val = pHead.val
                while pHead and val==pHead.val:
                    pHead = pHead.next
                last.next = pHead
            else:
                last = pHead
                pHead = pHead.next
        return first.next

二、字符串

面试题4:替换空格

题目描述:请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        s_list = list(s)
        for i in range(len(s_list)):
            if s[i] == ' ':
                s_list[i] = '%20'
        s1 = ''.join(s_list)
        return s1

面试题12:打印1到最大的n位数

题目:输入数字 n,按顺序打印出从 1 到最大的 n 位十进制数.比如输入 3,则打印出 1,2,3 一直到最大的 3 位数即 999 .

 

面试题28:字符串的排列

题目描述:输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。

输入描述:  输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。

# -*- coding:utf-8 -*-
class Solution:
    def Permutation(self, ss):
        list = []
        if len(ss) <= 1:
            return ss
        for i in range(len(ss)):
            for j in map(lambda x: ss[i]+x, self.Permutation(ss[:i]+ss[i+1:])):  #生成每个排好序的字符串(lambda补全每个循环中返回字符串的头部)
                if j not in list:   #这里的判断可以消除重复值的影响
                    list.append(j)
        return list
# -*- coding:utf-8 -*-
import itertools
# -*- coding:utf-8 -*-
class Solution:
    def Permutation(self, ss):
        # write code here
        if not ss:
            return ss
        a = itertools.permutations(ss)
        result = []
        for i in a:
            result.append(''.join(i))
        result = list(set(result))
        result.sort()
        return result

面试题32:从1到n整数中1出现的次数

题目描述:求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。

# -*- coding:utf-8 -*-
class Solution:
    def NumberOf1Between1AndN_Solution(self, n):
        num = 0
        for i in range(1,n+1):
            string = str(i)
            for j in range(len(string)):
                if string[j] == '1':
                    num += 1
        return num
# -*- coding:utf-8 -*-
class Solution:
    def NumberOf1Between1AndN_Solution(self, n):
        # write code here
        count = 0 #1的个数
        factor = 1 #当前位:个位,十位,百位等
        lowerNum = 0 #低位数字
        curNum = 0 #当前位
        higherNum = 0 #高位数字
        if n <= 0:
            return 0
        while n / factor != 0:
            lowerNum = n - (n / factor) * factor #最低位默认是0
            curNum = (n / factor) % 10
            higherNum = n / (factor * 10)
            if curNum == 0:
                count += higherNum * factor
            elif curNum == 1:
                count += higherNum * factor + lowerNum + 1
            else:
                count += (higherNum + 1) * factor
            factor *= 10
        return count

面试题35:第一个只出现1次的字符

题目描述:在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写)。

# -*- coding:utf-8 -*-
class Solution:
    def FirstNotRepeatingChar(self, s):
        # write code here
        dict = {}
        for ele in s:
            dict[ele] = 1 if ele not in dict else dict[ele] + 1
        for i in range(len(s)):
            if dict[s[i]] == 1:
                return i
        return -1

面试题42:反转单词顺序以及左旋转字符串

反转单词顺序:

题目描述:牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?

# -*- coding:utf-8 -*-
class Solution:
    def ReverseSentence(self, s):
        res = s.split( )
        if len(res) <= 1:
            return s
        right = ""
        for i in range(len(res)-1,-1,-1):
            if i > 0:
                right += res[i] + " "
            else:
                right += res[i]
        return right

左旋转字符串:

题目描述:汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!

# -*- coding:utf-8 -*-
class Solution:
    def LeftRotateString(self, s, n):
        # write code here
        res = []
        res.append(s[n:])
        res.append(s[:n])
        return res[0]+res[1]

面试题49:把字符串转换成整数

题目描述:将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。

输入描述:输入一个字符串,包括数字字母符号,可以为空

输出描述:如果是合法的数值表达则返回该数字,否则返回0

# -*- coding:utf-8 -*-
class Solution:
    def StrToInt(self, s):
        res,mult,flag = 0,1,1
        if not s:
            return res
        if s[0] == '-' or s[0] == '+':
            if s[0] == '-':
                flag = -1
            s = s[1:]
        for i in range(len(s)-1, -1, -1):
            if '9' >= s[i] >= '0':
                res += (ord(s[i]) - 48)*mult
                mult = mult * 10
            else:
                return 0
        return res*flag

面试题53:正则表达式匹配

题目描述:请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配

# -*- coding:utf-8 -*-
class Solution:
    # s, pattern都是字符串
    def match(self, s, pattern):
        # write code here
        if len(s) > 0 and len(pattern) == 0:
            return False
        if len(s) == 0 and len(pattern) == 0:
            return True
        if len(pattern) > 1 and pattern[1] == '*':
            if len(s) > 0 and (pattern[0] == s[0] or pattern[0] == '.'):
                return self.match(s, pattern[2:]) or self.match(s[1:], pattern)
            else:
                return self.match(s, pattern[2:])
        elif len(s) > 0 and (pattern[0] == s[0] or pattern[0] == '.'):
            return self.match(s[1:], pattern[1:])
        else:
            return False

面试题54:表示数值的字符串

题目描述:请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。

# -*- coding:utf-8 -*-
class Solution:
    # s字符串
    def isNumeric(self, s):
        # write code here
        try :
            p = float(s)
            return True
        except:
            return False

面试题55:字符流中第一个不重复的字符

题目描述:请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。

输出描述:如果当前字符流没有存在出现一次的字符,返回#字符。

# -*- coding:utf-8 -*-
class Solution:
    # 返回对应char
    def __init__(self):
        self.s = ''
        self.dict = {}
    def FirstAppearingOnce(self):
        # write code here
        for i in self.s:
            if self.dict[i] == 1:
                return i
        return '#'
    def Insert(self, char):
        # write code here
        self.s += char
        if char in self.dict:
            self.dict[char] += 1
        else:
            self.dict[char] = 1

三、栈和队列

面试题7:用两个栈实现队列&用两个队列实现栈

题目描述:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.stack1 = []
        self.stack2 = []
        
    def push(self, node):
        # write code here
        self.stack1.append(node)
        
    def pop(self):
        # return xx
        if self.stack2:
            return self.stack2.pop()
        else:
            while self.stack1:
                self.stack2.append(self.stack1.pop())
            return self.stack2.pop()

面试题21:包含min函数的栈

题目描述:定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.stack = []
        self.min_stack = []
        self.min_num = None

    def push(self, num):
        self.stack.append(num)
        if self.min_num is None:
            self.min_num = num
            self.min_stack.append(self.min_num)
        elif self.min_num < num:
                self.min_stack.append(self.min_num)
        else:
            self.min_num = num
            self.min_stack.append(num)

    def pop(self):
        if self.stack:
            self.min_stack.pop()
            return self.stack.pop()

    def min(self):
        return self.min_stack[-1]

面试题22:栈的压入、弹出序列

题目描述:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

# -*- coding:utf-8 -*-
class Solution:
    def IsPopOrder(self, pushV, popV):
        stack = []
        while popV:
            if stack and stack[-1] == popV[0]:
                stack.pop()
                popV.pop(0)
            elif pushV:
                stack.append(pushV.pop(0))
            else:
                return False
        return True

面试题65:滑动窗口的最大值

题目描述:给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。

 

四、树

面试题6:重建二叉树

题目描述:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回构造的TreeNode根节点
    def reConstructBinaryTree(self, pre, tin):
        # write code here
        if len(pre) == 0:
            return None
        elif len(pre) == 1:
            return TreeNode(pre[0])
        else:
            res = TreeNode(pre[0])
            res.left = self.reConstructBinaryTree(pre[1 : tin.index(pre[0])+1], tin[ : tin.index(pre[0])])
            res.right = self.reConstructBinaryTree(pre[tin.index(pre[0])+1:], tin[tin.index(pre[0])+1:])
        return res

面试题18:树的子结构

题目描述:输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def HasSubtree(self, pRoot1, pRoot2):
        # write code here
        result = False
        if pRoot1 and pRoot2:
            if pRoot1.val == pRoot2.val:
                result = self.isequal(pRoot1, pRoot2)
            if not result:
                result = self.HasSubtree(pRoot1.left, pRoot2)
            if not result:
                result = self.HasSubtree(pRoot1.right, pRoot2)

        return result

    def isequal(self, root1, root2):
        if not root2:
            return True
        if not root1:
            return False
        if root1.val != root2.val:
            return False
        return self.isequal(root1.left, root2.left) and self.isequal(root1.right, root2.right)

面试题19:二叉树镜像

题目描述:操作给定的二叉树,将其变换为源二叉树的镜像。

输入描述:

二叉树的镜像定义:源二叉树 
    	    8
    	   /  \
    	  6   10
    	 / \  / \
    	5  7 9 11
    	镜像二叉树
    	    8
    	   /  \
    	  10   6
    	 / \  / \
    	11 9 7  5
# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回镜像树的根节点
    def Mirror(self, root):
        # write code here
        if not root:
            return None
        root.left, root.right = root.right, root.left
        if root.right:
                self.Mirror(root.right)
        if root.left:
                self.Mirror(root.left)

面试题23:从上往下打印二叉树

题目描述:从上往下打印出二叉树的每个节点,同层节点从左至右打印。

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回从上到下每个节点值列表,例:[1,2,3]
    def PrintFromTopToBottom(self, root):
        # write code here
        queue = []
        result = []
        if root == None:
            return result

        queue.append(root)
        while queue:
            newNode = queue.pop(0)
            result.append(newNode.val)
            if newNode.left != None:
                queue.append(newNode.left)
            if newNode.right != None:
                queue.append(newNode.right)
        return result

面试题24:二叉搜索树的后序遍历

题目描述:输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。

# -*- coding:utf-8 -*-
class Solution:
    def VerifySquenceOfBST(self, sequence):
        # write code here
        if not len(sequence):
            return False
        if len(sequence) == 1:
            return True
        length = len(sequence)
        root = sequence[-1]
        i = 0
        while sequence[i] < root:
            i = i + 1
        k = i
        for j in range(i, length-1):
            if sequence[j] < root:
                return False
        left_s = sequence[:k]
        right_s = sequence[k:length-1]
        left, right = True, True
        if len(left_s) > 0:
            left = self.VerifySquenceOfBST(left_s)
        if len(right_s) > 0:
            right = self.VerifySquenceOfBST(right_s)
        return left and right

面试题25:二叉树中和为某一值的路径

题目描述:输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)

 

面试题27:二叉搜索树与双向链表

题目描述:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

 

面试题39:二叉树的深度

题目描述:输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

 

面试题50:树中两个节点的最低公共祖先

 

面试题58:二叉树的下一个节点

题目描述:给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。

解释:这个结点如果有右结点,则下一个结点是右结点

         如果没有右结点:

                                    如果她是她父结点的左子树,则下一结点是父结点

                                     否则已知上溯找是父结点的左子树的点,否则None

# -*- coding:utf-8 -*-
# class TreeLinkNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#         self.next = None
class Solution:
    def GetNext(self, pNode):
        # write code here
        if pNode.right:
            pNode = pNode.right
            while pNode.left:
                pNode = pNode.left
            return pNode
        else:
            while pNode.next:
                if pNode.next.left == pNode:
                    return pNode.next
                pNode = pNode.next
        return None

面试题59:对称的二叉树

题目描述:请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

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

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        if not root:
            return True
        return self.isequal(root.left, root.right)
    
    def isequal(self, left, right):
        if not left and not right:
            return True
        if not left or not right:
            return False
        l = self.isequal(left.left, right.right)
        r = self.isequal(right.left, left.right)
        return l and r and left.val == right.val

 

面试题60:把二叉树打印成多行

题目描述:从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

 

面试题61:按之字形顺序打印二叉树

题目描述:请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。

 

面试题62:序列化二叉树

题目描述:请实现两个函数,分别用来序列化和反序列化二叉树

 

面试题63:二叉搜索树的第k个结点

题目描述:给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8)    中,按结点数值大小顺序第三小结点的值为4。

 

牛客剑指题:平衡二叉树

题目描述:输入一棵二叉树,判断该二叉树是否是平衡二叉树。

 

五、查找和排序

面试题8:旋转数组中的最小数字

题目描述:把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。

# -*- coding:utf-8 -*-
class Solution:
    def minNumberInRotateArray(self, rotateArray):
        if len(rotateArray) == 0:
            return 0
        for i in range(len(rotateArray)):
            if rotateArray[i+1] < rotateArray[i]:
                return rotateArray[i+1]

六、动态规划

面试题9:斐波那契数列

# -*- coding:utf-8 -*-
class Solution:
    def Fibonacci(self, n):
        # write code here
        res = []
        if n <= 1:
            return n
        else:
            res.append(0)
            res.append(1)
        if n == 2:
            return 1
        else:
            res.append(1)
        for i in range(3, n+1):
            res.append(res[i-1] + res[i-2])
        return res[n]

面试题31:连续子数组的最大和

题目描述:HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。给一个数组,返回它的最大连续子序列的和,你会不会被他忽悠住?(子向量的长度至少是1)

动态规划求解:(O(n))

# -*- coding:utf-8 -*-
class Solution:
    def FindGreatestSumOfSubArray(self, array):
        # write code here
        for i in range(1, len(array)):
            max_sum = max(array[i-1] + array[i], array[i])
            array[i] = max_sum
        return max(array)

面试题34:丑数

题目描述:把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。

# -*- coding:utf-8 -*-
class Solution:
    def GetUglyNumber_Solution(self, index):
        # write code here
        if index == 0:
            return 0
        res = []
        res.append(1)
        index1 = 0
        index2 = 0
        index3 = 0
        for i in range(index-1):
            min_res = min(res[index1]*2, res[index2]*3, res[index3]*5)
            res.append(min_res)
            if res[index1] * 2 == min_res:
                index1 += 1
            if res[index2] * 3 == min_res:
                index2 += 1
            if res[index3] * 5 == min_res:
                index3 += 1
        return res[-1]

面试题45:圆圈中最后剩下的数字(约瑟夫环问题)

题目描述:每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0...m-1报数....这样下去....直到剩下最后一个小朋友,可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1)

 

七、回朔法

面试题66:矩阵中的路径

题目描述:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

 

面试题67:机器人的运动范围

题目描述:地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?

# -*- coding:utf-8 -*-
class Solution:
    def hasPath(self, matrix, rows, cols, path):
        # write code here
        for i in range(0,rows):
            for j in range(0,cols):
                flags = [0] * (rows * cols)
                if self.isPath(matrix,i,j,rows,cols,path,flags,0):
                    return True
        return False
    def isPath(self,matrix,row,col,rows,cols,path,flags,index):
        if index == len(path):
            return True
        if row >= rows or col >= cols or row < 0 or col < 0 or flags[row*cols + col]:
            return False
        if matrix[row*cols + col] == path[index]:
            flags[row*cols + col] = 1
            return self.isPath(matrix,row + 1,col,rows,cols,path,flags, index + 1) or self.isPath(matrix,row - 1,col,rows,cols,path,flags,index + 1) or self.isPath(matrix,row,col + 1,rows,cols,path,flags, index + 1) or self.isPath(matrix,row,col - 1,rows,cols,path,flags, index + 1)
        else:
            return False

八、细节实现题

面试题10:二进制中1的个数

题目描述:输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

# -*- coding:utf-8 -*-
class Solution:
    def NumberOf1(self, n):
        j = 0
        for i in range(32):
            if n%2 == 1:
                j += 1
            n = n//2
        return j
# -*- coding:utf-8 -*-
class Solution:
    def NumberOf1(self, n):
        # write code here
        return sum([(n>>i & 1) for i in range(0,32)])

面试题11:数值的整数次方

题目描述:给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。

# -*- coding:utf-8 -*-
class Solution:
    def Power(self, base, exponent):
        return base**float(exponent)
# -*- coding:utf-8 -*-
class Solution:
    def Power(self, base, exponent):
        # write code here
        flag = 0
        if base == 0:
            return False
        if exponent == 0:
            return 1
        if exponent < 0:
            flag = 1
        result = 1
        for i in range(abs(exponent)):
            result *= base
        if flag == 1:
            result = 1 / result
        return result

面试题20:顺时针打印矩阵

题目描述:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

# -*- coding:utf-8 -*-
class Solution:
    # matrix类型为二维列表,需要返回列表
    def printMatrix(self, matrix):
        raw = len(matrix)
        col = len(matrix[0])
        res = []
        if raw == 0 and col == 0:
            return res
        left, right, top, bottom = 0, col-1, 0, raw-1
        while left<=right and top<=bottom:
            for i in range(left, right+1):
                res.append(matrix[top][i])
            for i in range(top+1, bottom+1):
                res.append(matrix[i][right])
            if top != bottom:
                for i in range(right-1, left-1, -1):
                    res.append(matrix[bottom][i])
            if left != right:
                for i in range(bottom-1, top, -1):
                    res.append(matrix[i][left])
            left += 1
            top += 1
            right -= 1
            bottom -= 1
        return res
# -*- coding:utf-8 -*-
class Solution:
    # matrix类型为二维列表,需要返回列表
    def printMatrix(self, matrix):
        # write code here
        result=[]
        while matrix:
            result=result+matrix.pop(0)
            if not matrix:
                break
            matrix=self.turn(matrix)
        return result
    def turn(self, matrix):
        r=len(matrix)
        c=len(matrix[0])
        B=[]
        for i in range(c):
            A=[]
            for j in range(r):
                A.append(matrix[j][i])
            B.append(A)
        B.reverse()
        return B

面试题41:和为s的两个数字VS和为s的连续正数序列

和为s的两个数字:

题目描述:输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。

输出描述:对应每个测试案例,输出两个数,小的先输出。

# -*- coding:utf-8 -*-
class Solution:
    def FindNumbersWithSum(self, array, tsum):
        b = []
        c = []
        num = 0
        length = len(array)
        for i in range(length):
            for j in range(i+1,length):
                a =[]
                if array[i] + array[j] > tsum:
                    length = j+1
                sum = array[i] + array[j]
                if sum == tsum:
                    a.append(array[i])
                    a.append(array[j])
                    b.append(a)
                    break
        if len(b) == 0:
            return []
        else:
            return b[0]
from collections import Counter
class Solution:
    def FindNumbersWithSum(self, array, tsum):
        # write code here
        m = Counter(array)
         
        for i in array:
            if tsum-i in m:
                if i!=tsum-i:
                    return (i,tsum-i)
                if m[i]>1:
                    return (i,i)
        return []

为s的连续正数序列:

题目描述:小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!

输出描述:输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序

# -*- coding:utf-8 -*-
class Solution:
    def FindContinuousSequence(self, tsum):
        b = []
        if tsum < 3:
            return []
        for i in range(1, tsum/2+1):
            for j in range(i+1, tsum/2+2):
                a = []
                n = j-i+1
                Sn = n*i + n*(n-1)/2
                if Sn == tsum:
                    for m in range(i,j+1):
                        a.append(m)
                    b.append(a)
                    break
        return b

面试题43:n个骰子的点数

面试题44:扑克牌顺子

题目描述:LL今天心情特别好,因为他去买了一副扑克牌,发现里面居然有2个大王,2个小王(一副牌原本是54张^_^)...他随机从中抽出了5张牌,想测测自己的手气,看看能不能抽到顺子,如果抽到的话,他决定去买体育彩票,嘿嘿!!“红心A,黑桃3,小王,大王,方片5”,“Oh My God!”不是顺子.....LL不高兴了,他想了想,决定大\小 王可以看成任何数字,并且A看作1,J为11,Q为12,K为13。上面的5张牌就可以变成“1,2,3,4,5”(大小王分别看作2和4),“So Lucky!”。LL决定去买体育彩票啦。 现在,要求你使用这幅牌模拟上面的过程,然后告诉我们LL的运气如何, 如果牌能组成顺子就输出true,否则就输出false。为了方便起见,你可以认为大小王是0。

# -*- coding:utf-8 -*-
class Solution:
    def IsContinuous(self, numbers):
        # write code here
        if len(numbers) < 1:
            return False
        new_nums = [i for i in numbers if i > 0]
        max_n = max(numbers)
        min_n = min(new_nums)
        d = []
        if max_n - min_n < 5:
            for i in numbers:
                if i != 0 and (i in d):
                    return False
                else:
                    d.append(i)
        else:
            return False
        return True

面试题46:求1+2+3+.......+n

题目描述:求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。

# -*- coding:utf-8 -*-
class Solution:
    def Sum_Solution(self, n):
        # write code here
        return n and (n+self.Sum_Solution(n-1))

面试题47:不用加减乘除做加法

题目描述:写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。

# -*- coding:utf-8 -*-
class Solution:
    def Add(self, num1, num2):
        # write code here
        s=[]
        s.append(num1)
        s.append(num2)
        return sum(s)

面试题64:数据流中的中位数(树)

题目描述:如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.data = []
        
    def Insert(self, num):
        # write code her
        self.data.append(num)
        self.data.sort()
        
    def GetMedian(self, data):
        # write code here
        length = len(self.data)
        if length%2 == 1:
            return self.data[length//2]
        else:
            return (self.data[length//2] + self.data[length//2-1])/2.0

Leetcode:

104. 二叉树的最大深度

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

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
        else:
            return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))

 

107. 二叉树的层次遍历 II

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

class Solution:
    def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
        queue = [root]
        res = []
        if not root:
            return []
        while queue:
            tmplist = []
            l = len(queue)
            for i in range(l):
                tmp = queue.pop(0)
                tmplist.append(tmp.val)
                if tmp.left:
                    queue.append(tmp.left)
                if tmp.right:
                    queue.append(tmp.right)
            res.append(tmplist)
        return res[::-1]

108. 将有序数组转换为二叉搜索树

 

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

class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
        if len(nums) == 0:
            return 
        mid = len(nums)//2
        pNode = TreeNode(nums[mid])
        pNode.left = self.sortedArrayToBST(nums[:mid])
        pNode.right = self.sortedArrayToBST(nums[mid+1:])
        return pNode
        

 110. 平衡二叉树

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

class Solution:
    def isBalanced(self, root: TreeNode) -> bool:
        if not root:
            return True
        elif abs(self.Deepth(root.left) - self.Deepth(root.right)) > 1:
            return False
        else:
            return self.isBalanced(root.left) and self.isBalanced(root.right)
        
    def Deepth(self, root):
        if not root:
            return 0
        return 1 + max(self.Deepth(root.left), self.Deepth(root.right))

111. 二叉树的最小深度

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

class Solution:
    def minDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
        elif not root.left and not root.right:
            return 1
        elif not root.right:
            return 1 + self.minDepth(root.left)
        elif not root.left:
            return 1 + self.minDepth(root.right)
        else:
            return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
        

112.路径总和

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

class Solution:
    def hasPathSum(self, root: TreeNode, sum: int) -> bool:
        if not root:
            return False
        elif sum == root.val and not root.left and not root.right:
            return True
        else:
            return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val)

118.杨辉三角

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        if numRows == 0:
            return []
        if numRows == 1:
            return [[1]]
        elif numRows == 2:
            return [[1], [1,1]]
        res = [[1],[1, 1]]
        tmp = [1]
        for i in range(1, numRows-1):
            for j in range(i):
                tmp.append(res[-1][j] + res[-1][j+1])
            tmp.append(1)
            res.append(tmp)
            tmp = [1]
        return res

119.杨辉三角Ⅱ

class Solution:
    def getRow(self, rowIndex: int) -> List[int]:
        if rowIndex == 0:
            return [1]
        if rowIndex == 1:
            return [1,1]
        res = [1, 1]
        tmp = [1]
        for i in range(rowIndex):
            for j in range(i):
                tmp.append(res[j] + res[j+1])
            tmp.append(1)
            res = tmp
            tmp = [1]
        return res

121.买卖股票的最佳时机

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if len(prices) == 0:
            return 0
        cost = prices[0]
        profit = 0
        for price in prices:
            cost = min(price, cost)
            profit = max(price-cost, profit)
        return profit

122.买卖股票的最佳时机

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if len(prices) == 0:
            return 0
        cost = prices[0]
        res = 0
        for price in prices:
            profit = price-cost
            cost = price
            if profit > 0:
                res += profit
        return res

125.验证回文串

class Solution:
    def isPalindrome(self, s: str) -> bool:
        str = ''
        for i in s:
            if i.isalnum():
                str+=i
        i = 0
        j = len(str)-1
        while i < j:
            if str[i].lower() != str[j].lower():
                    return False
            i += 1
            j -= 1
        return True

136.只出现一次的数字

# class Solution:
#     def singleNumber(self, nums: List[int]) -> int:
#         res = []
#         for i in nums:
#             if i in res:
#                 res.remove(i)
#             else:
#                 res.append(i)
#         return res[0]
class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        has_table = {}
        for i in nums:
            try:
                has_table.pop(i)
            except:
                has_table[i] = 1
        return has_table.popitem()[0]

141.环形链表

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

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        fast = head
        slow = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
            if slow == fast:
                return True
        return False

155.最小栈

class MinStack(object):

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.data = []
        self.tmp = []

    def push(self, x):
        """
        :type x: int
        :rtype: None
        """
        if len(self.tmp) == 0 or self.tmp[-1] >= x:
            self.tmp.append(x)
        self.data.append(x)

    def pop(self):
        """
        :rtype: None
        """
        top = self.data.pop()
        if self.tmp and top == self.tmp[-1]:
            self.tmp.pop()
        return top

    def top(self):
        """
        :rtype: int
        """
        if self.data:
            return self.data[-1]

    def getMin(self):
        """
        :rtype: int
        """
        if self.tmp:
            return self.tmp[-1]


# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()

160.相交链表

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

class Solution(object):
    def length(self, head):
        i = 0
        while head:
            head = head.next
            i += 1
        return i
    
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        l1, l2 = self.length(headA), self.length(headB)
        if l1 < l2:
            l1, l2 = l2, l1
            headA, headB = headB, headA
        while l1-l2:
            headA = headA.next
            l1 -= 1
        while headA != headB:
            headA = headA.next
            headB = headB.next
        return headA
            

167.两数之和Ⅱ-输入有序数组

class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        left, right = 0, len(numbers)-1
        while left < right:
            if numbers[left]+numbers[right] < target:
                left += 1
            elif numbers[left]+numbers[right] > target:
                right -= 1
            else:
                return [left+1, right+1]
        return []

168.excel表列名称

class Solution(object):
    def convertToTitle(self, n):
        """
        :type n: int
        :rtype: str
        """
        # if n<=0:
        #     return None
        # numA = ord('A')
        # res = ''
        # while n//26 > 0:
        #     res = chr((n-1)%26 + numA) + res
        #     n = (n-1)//26
        # if n != 0:
        #     res = chr(n-1+numA) + res
        # return res
        excel = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
        res = ''
        while(n):
            n -= 1
            res = excel[n%26] + res
            n = n//26
        return res

169.求众数

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        count = 0
        for i in nums:
            if count == 0:
                tmp = i
            if i == tmp:
                count += 1
            else:
                count -= 1
        return tmp
        

171.Excel表列序号

class Solution(object):
    def titleToNumber(self, s):
        """
        :type s: str
        :rtype: int
        """
        res = 0
        tmp = 0
        for i in range(len(s)):
            tmp = ord(s[i])-ord('A')+1
            res = res*26 + tmp
        return res

172.阶乘后的零

class Solution(object):
    def trailingZeroes(self, n):
        """
        :type n: int
        :rtype: int
        """
        res = 0
        while n >= 5:
            res += n//5
            n = n//5
        return res

189.旋转数组

class Solution(object):
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        # a = [0 for i in range(len(nums))]
        # for i in range(len(nums)):
        #     a[(i+k)%len(nums)] = nums[i]
        # for i in range(len(nums)):
        #     nums[i] = a[i]
        # return nums
        k %= len(nums)
        nums[:] = nums[len(nums)-k:] + nums[:len(nums)-k]
        

190.颠倒二进制位

class Solution:
    # @param n, an integer
    # @return an integer
    def reverseBits(self, n):
        return int(bin(n)[2:].zfill(32)[::-1], base=2)

191.位1 的个数

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        count = 0
        while n:
            count += n&1
            n >>= 1
        return count

198.打家劫舍

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        n = len(nums)
        if n == 0:
            return 0
        if n <= 2:
            return max(nums)
        i = 3
        dp = [nums[0]] + [max(nums[0], nums[1])] + [nums[0]+nums[2]] + (n-3)*[0]
        while i < n:
            dp[i] = max(dp[i-2]+nums[i], dp[i-3]+nums[i])
            i += 1
        return max(dp)
        

202.快乐数

class Solution(object):
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        dic = [1]
        while n not in dic:
            dic.append(n)
            n = (sum(int(i)**2 for i in str(n)))
        return n==1

203.移除链表元素

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

class Solution(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        pnode = ListNode(None)
        pnode.next = head
        q = pnode
        while q.next:
            if q.next.val == val:
                q.next = q.next.next
            else:
                q = q.next
        return pnode.next

204.计数质数

class Solution(object):
    def countPrimes(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n<2:
            return 0
        res = [1]*n
        res[0], res[1] = 0, 0
        for i in range(2, int(n**0.5)+1):
            if res[i]:
                res[i*2:n:i] = [0]*len(res[i*2:n:i])
        return sum(res)
        

205.同构字符串

class Solution(object):
    def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        res_s = self.convert(s)
        res_t = self.convert(t)
        if res_s == res_t:
            return True
        else:
            return False
    def convert(self, ch):
        dic = {}
        j = 0
        for i in ch:
            if i not in dic:
                dic[i] = j
                j += 1
        res = []
        for i in ch:
            res.append(dic[i])
        return res

206.反转链表

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

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return None
        pre = None
        while head.next:
            tmp = head.next
            head.next = pre
            pre = head
            head = tmp
        head.next = pre
        return head

217.存在重复元素

class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        if len(nums) == len(set(nums)):
            return False
        else:
            return True

217.存在重复元素Ⅱ

class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        dic = {}
        for i in range(len(nums)):
            if nums[i] not in dic:
                dic[nums[i]] = i
            elif abs(i-dic[nums[i]]) <= k:
                return True
            else:
                dic[nums[i]] = i
        return False

225.用队列实现栈

226.翻转二叉树

# 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 not root:
            return None
        root.left, root.right = root.right, root.left
        root.left = self.invertTree(root.left)
        root.right = self.invertTree(root.right)
        return root

231.2的幂

class Solution(object):
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n == 1:
            return True
        if n == 0:
            return False
        while n%2 == 0:
            n //= 2
        if n == 1:
            return True
        else:
            return False

232.用栈实现队列

234.回文链表

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

class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        # res = []
        # while head:
        #     res.append(head.val)
        #     head = head.next
        # for i in range(len(res)/2):
        #     if res[i] != res[len(res)-i-1]:
        #         return False
        # return True
        if not head or not head.next:
            return True
        slow, fast = head, head
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
        re = self.convert(slow.next)
        while re.next:
            if head.val != re.val:
                return False
            head = head.next
            re = re.next
        return re.val == head.val
    def convert(self, head):
        if not head:
            return None
        p = None
        while head.next:
            tmp = head.next
            head.next = p
            p = head
            head = tmp
        head.next = p
        return head

235.二叉搜索树的最近公共祖先

# 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 lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        if p.val < root.val and q.val < root.val:
            return self.lowestCommonAncestor(root.left, p, q)
        elif p.val > root.val and q.val > root.val:
            return self.lowestCommonAncestor(root.right, p, q)
        else:
            return root
                

237.删除链表中的节点

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

class Solution(object):
    def deleteNode(self, node):
        """
        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """
        node.val = node.next.val
        node.next = node.next.next

242.有效的字母异位词

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s) != len(t):
            return False
        c = set(s)
        for i in c:
            if t.count(i) != s.count(i):
                return False
        return True

257.二叉树的所有路径

# 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 binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """
        if not root:
            return []
        if not root.left and not root.right:
            return [str(root.val)]
        path = []
        if root.left:
            for i in self.binaryTreePaths(root.left):
                path.append(str(root.val) + '->' + i)
        if root.right:
            for i in self.binaryTreePaths(root.right):
                path.append(str(root.val) + '->' + i)
        return path

258.各位相加

class Solution(object):
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        # if num > 9:
        #     num = num%9
        #     if num == 0:
        #         return 9
        # return num
        if num//10 == 0:
            return num
        res = 0
        num = str(num)
        for i in range(len(num)):
            res += int(num[i])
        return self.addDigits(res)

263.丑数

class Solution(object):
    def isUgly(self, num):
        """
        :type num: int
        :rtype: bool
        """
        if num:
            while num % 5 == 0:
                num = num // 5
            while num % 3 == 0:
                num = num // 3
            while num % 2 == 0:
                num = num // 2
        return num == 1

268.缺失数字

class Solution(object):
    def missingNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums = sorted(nums)
        if nums[-1] != len(nums):
            return len(nums)
        elif nums[0] != 0:
            return 0
        for i in range(len(nums)):
            if nums[i+1]-nums[i] > 1:
                return nums[i+1]-1

278.第一个错误的版本

# The isBadVersion API is already defined for you.
# @param version, an integer
# @return a bool
# def isBadVersion(version):

class Solution(object):
    def firstBadVersion(self, n):
        """
        :type n: int
        :rtype: int
        """
        left, right = 1, n
        while left <= right:
            mid = (left+right)//2
            if isBadVersion(mid):
                if not isBadVersion(mid-1):
                    return mid
                else:
                    right = mid-1
            else:
                left = mid+1

283.移动零

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        j = 0
        for i in range(len(nums)):
            if nums[i] != 0:
                nums[j] = nums[i]
                j += 1
        while j < len(nums):
            nums[j] = 0
            j += 1
        return nums

290.单词规律

class Solution(object):
    def wordPattern(self, pattern, str):
        """
        :type pattern: str
        :type str: str
        :rtype: bool
        """
        s = str.split(' ')
        res = self.pattern_s(s)
        pattern = self.pattern_s(pattern)
        return res == pattern
    
    def pattern_s(self, s):
        dic = {}
        res = ''
        j = 0
        for i in s:
            if i not in dic:
                dic[i] = j
                res = res + str(j)
                j += 1
            else:
                res = res + str(dic[i])
        return res

292.Nim游戏

class Solution(object):
    def canWinNim(self, n):
        """
        :type n: int
        :rtype: bool
        """
        return n%4 != 0

303.区域和检索 - 数组不可变

class NumArray(object):

    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        self.nums = nums
        target = []
        sumnum = 0
        for num in self.nums:
            sumnum += num
            target.append(sumnum)
        self.target = target
        
    def sumRange(self, i, j):
        """
        :type i: int
        :type j: int
        :rtype: int
        """
        return self.target[j]-self.target[i]+self.nums[i]

# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(i,j)

326.3的幂

import math
class Solution(object):
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n <= 0:
            return False
        if abs(math.log(n, 3)-round(math.log(n, 3)))<=0.0000000001:
            return True
        else:
            return False

342.4的幂

import math
class Solution(object):
    def isPowerOfFour(self, num):
        """
        :type num: int
        :rtype: bool
        """
        if num <= 0:
            return False
        if abs(math.log(num, 4)-round(math.log(num, 4)))<=0.0000000001:
            return True
        else:
            return False

344.反转字符串

class Solution(object):
    def reverseString(self, s):
        """
        :type s: List[str]
        :rtype: None Do not return anything, modify s in-place instead.
        """
        l = len(s)-1
        for i in range(l//2+1):
            s[i], s[l-i] = s[l-i], s[i]
        return s

345.反转字符串中的元音字母

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        yuan = 'aeiouAEIOU'
        left, right = 0, len(s)-1
        s = list(s)
        while left < right:
            if s[left] in yuan and s[right] in yuan:
                s[left], s[right] = s[right], s[left]
                left += 1
                right -= 1
            elif s[left] in yuan:
                right -= 1
            elif s[right] in yuan:
                left += 1
            else:
                left += 1
                right -= 1
        res = ''.join(s)
        return res

349.两个数组的交集

class Solution(object):
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        res = []
        if len(nums1) < len(nums2):
            nums1, nums2 = nums2, nums1
        for i in range(len(nums1)):
            if nums1[i] in nums2:
                res.append(nums1[i])
        return set(res)

350.两个数组的交集Ⅱ

class Solution(object):
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        nums1.sort()
        nums2.sort()
        res = []
        i, j = 0, 0
        while i < len(nums1) and j < len(nums2):
            if nums1[i] < nums2[j]:
                i += 1
            elif nums1[i] > nums2[j]:
                j += 1
            else:
                res.append(nums1[i])
                i += 1
                j += 1
        return res
            

367.有效的完全平方数

class Solution(object):
    def isPerfectSquare(self, num):
        """
        :type num: int
        :rtype: bool
        """
        if num == 1:
            return True
        left, right = 0, num
        while left < right:
            mid = (left+right)//2
            if mid**2 < num:
                left = mid+1
            elif mid**2 > num:
                right = mid
            else:
                return True
        return False

371.两整数之和 sum(),位运算

374.猜数字大小

# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num):

class Solution(object):
    def guessNumber(self, n):
        """
        :type n: int
        :rtype: int
        """
        if guess(n) == 0:
            return n
        left, right =0, n
        while left < right:
            mid = (left+right)//2
            if guess(mid) == -1:
                right = mid
            elif guess(mid) == 1:
                left = mid
            elif guess(mid) == 0:
                return mid
        return -1

383.赎金信

class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        s1 = list(ransomNote)
        s2 = list(magazine)
        for i in s1:
            if i in s2 and s1.count(i) <= s2.count(i):
                continue
            else:
                return False
        return True

387.字符串中的第一个唯一字符

class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        dic = {}
        for i in s:
            if i not in dic:
                dic[i] = 1
            else:
                dic[i] += 1
        for i in range(len(s)):
            if dic[s[i]] == 1:
                return i
        return -1

389.找不同

class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        dic = {}
        for i in list(s):
            if i not in dic:
                dic[i] = 1
            else:
                dic[i] += 1
        for i in list(t):
            if i not in dic:
                return i
            elif dic[i] + 1 == list(t).count(i):
                return i
        return False

400.第N个数字

401.二进制手表

404.左叶子之和

# 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 sumOfLeftLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        if root.left and not root.left.left and not root.left.right:
            return root.left.val + self.sumOfLeftLeaves(root.right)
        else:
            return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)

405数字转换为十六进制数

class Solution(object):
    def toHex(self, num):
        """
        :type num: int
        :rtype: str
        """
        dic = {0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: 'a', 11: 'b', 12: 'c', 13: 'd', 14: 'e', 15: 'f'}
        if num == 0:
            return '0'
        res = []
        if num < 0:
            num += 2**32
        while num > 0:
            res.append(dic[num%16])
            num = num//16
        res.reverse()
        return ''.join(res)

409.最长回文串

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: int
        """
        res = 0
        arr = []
        Flag = False
        for i in s:
            tmp = s.count(i)
            if tmp > 1 and tmp%2 == 0 and i not in arr:
                res += tmp
                arr.append(i)
            elif tmp > 1 and tmp%2 != 0 and i not in arr:
                res += tmp-1
                Flag = True
                arr.append(i)
            elif tmp == 1:
                Flag = True
        if Flag:
            return res+1
        else:
            return res

412.Fizz Buzz

class Solution(object):
    def fizzBuzz(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        res = []
        for i in range(1, n+1):
            if i%3 == 0 and i%5 == 0:
                res.append('FizzBuzz')
            elif i%5 == 0:
                res.append('Buzz')
            elif i%3 == 0:
                res.append('Fizz')
            else:
                res.append(str(i))
        return res

414.第三大的数

class Solution(object):
    def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 0:
            return []
        nums = set(nums)
        if len(nums) < 3:
            return max(nums)
        nums = list(nums)
        nums.sort(reverse = True)
        return nums[2]

415.字符串相加

class Solution(object):
    def addStrings(self, nums1, nums2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        res = ''
        i, j, carry = len(nums1)-1, len(nums2)-1, 0
        while i >= 0 or j >= 0:
            a = ord(nums1[i]) - ord('0') if i >= 0 else 0
            b = ord(nums2[j]) - ord('0') if j >= 0 else 0
            tmp = a + b + carry
            carry = tmp//10
            res = str(tmp%10) + res
            i -= 1
            j -= 1
        if carry: res = '1' + res
        return res

429.N叉树的层序遍历

"""
# Definition for a Node.
class Node(object):
    def __init__(self, val, children):
        self.val = val
        self.children = children
"""
class Solution(object):
    def levelOrder(self, root):
        """
        :type root: Node
        :rtype: List[List[int]]
        """
        if not root:
            return root
        queue = []
        res = []
        queue.append(root)
        while len(queue):
            sub = []
            for i in range(len(queue)):
                cur = queue.pop(0)
                sub.append(cur.val)
                for child in cur.children:
                    queue.append(child)
            res.append(sub)
        return res

434.字符串中的单词数

class Solution(object):
    def countSegments(self, s):
        """
        :type s: str
        :rtype: int
        """
        res = 0
        for i in range(len(s)):
            if (i == 0 or s[i-1] == ' ') and s[i] != ' ':
                res += 1
        return res

437.路径总和Ⅲ

# 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 pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: int
        """
        res = 0
        if not root:
            return res
        res += self.sumroot(root, sum)
        res += self.pathSum(root.left, sum)
        res += self.pathSum(root.right, sum)
        return res
    
    def sumroot(self, root, sum):
        count = 0
        if not root:
            return 0
        if root.val == sum:
            count += 1
        count += self.sumroot(root.left, sum-root.val)
        count += self.sumroot(root.right, sum-root.val)
        return count
                

438.找到字符串中所有字母异位词

自己超出时间的

class Solution(object):
    def findAnagrams(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: List[int]
        """
        left = 0
        res = []
        if len(s) < len(p):
            return []
        while left <= len(s)-len(p):
            a = set(p)
            b = set(s[left:left+len(p)])
            if len(a) != len(b):
                left += 1
                continue
            count = 0
            for i in a:
                if p.count(i) == s[left:left+len(p)].count(i):
                    count += 1
                else:
                    break
            if count == len(a):
                res.append(left)
            left += 1
        return res

网上思路:

class Solution:
    def findAnagrams(self, s: str, p: str) -> List[int]:
        
        # 思路:
        # 想象一个窗口在s上向右移动,窗口宽度为len(p)
        # 只要窗口内的字符串各字符数量与p中一致,则匹配成功
        # 窗口在向右移动的时候,只需要将最左端的值从字典中删除,将最右端+1的值加入字典即可.

    
    
        pmap = {}
        for i in p:
            pmap[i] = pmap.get(i,0) + 1
        plenth = len(p)

        rlist = []
        rmap = {}
        
        
        for i , v in enumerate(s):
            rmap[v] = rmap.get(v,0) + 1
            if rmap == pmap:
                rlist.append(i-plenth+1)
            if i - plenth + 1 >= 0:
                rmap[s[i-plenth + 1]] = rmap.get(s[i-plenth + 1]) - 1
                if rmap[s[i-plenth + 1]] == 0:
                    del rmap[s[i-plenth + 1]]
               
        return rlist

441.排列硬币

class Solution(object):
    def arrangeCoins(self, n):
        """
        :type n: int
        :rtype: int
        """
        # tmp = 0
        # while tmp*(tmp+1)//2 <= n:
        #     if tmp*(tmp+1)//2 == n:
        #         return tmp
        #     else:
        #         tmp += 1
        # return tmp-1
        left, right = 0, n
        while left <= right:
            mid = (left+right)//2
            if mid*(mid+1)//2 <= n and (mid+1)*(mid+2)//2 > n:
                return mid
            elif mid*(mid+1)//2 > n:
                right = mid - 1
            elif mid*(mid+1)//2 < n:
                left = mid + 1

443.压缩字符串

class Solution(object):
    def compress(self, chars):
        """
        :type chars: List[str]
        :rtype: int
        """ 
        if len(chars) == 1:
            return 1
        write = 0
        read = 0
        nextread = 0
        count = 0
        while read < len(chars):
            if nextread < len(chars) and chars[read] == chars[nextread]:
                nextread += 1
                count += 1
            else:
                chars[write] = chars[read]
                write += 1
                read = nextread
                if count > 1:
                    for i in str(count):
                        chars[write] = i
                        write += 1
                count = 0
        return write

447.回旋镖的数量

class Solution(object):
    def numberOfBoomerangs(self, points):
        """
        :type points: List[List[int]]
        :rtype: int
        """
        res = 0
        for i in points:
            dic = {}
            for j in points:
                dis = (i[0]-j[0])**2 + (i[1]-j[1])**2
                if dis not in dic:
                    dic[dis] = 1
                else:
                    dic[dis] += 1
            for val in dic.values():
                if val >= 2:
                    res += val*(val-1)
        return res

448.找到所有数组中消失的数字

class Solution(object):
    def findDisappearedNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        for num in nums:
            index = abs(num)-1
            nums[index] = -abs(nums[index])
        return [i + 1 for i, num in enumerate(nums) if num > 0]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值