2018-05-03

刷了牛客网的题目:总结思路(总的思路跟数学一样就是化简和转化)

具体启发点:

1.对数据进行预处理排序的思想:比如8皇后问题

2.对一个数组元素进行比较的操作,如果复杂,可以试试倒过来,从最后一个元素往前面想.

3.动态规划,分治法.

4.超复杂的循环最好的方法是while 1:这种写法.(因为他最大程度保证了灵活性,比如leecode的283题)

leecode习题: 主要是目前在学习 玩转算法面试 leetcode 这个课程,他把leecode的题目做分类,将例题,留习题.我就把所有的例题和习题都自己实现以下.写在下面

就算以后做垃圾码农,也要留下这些题目我的脚印

数组问题:

283

  1. '''
  2. . 移动零
  3. 题目描述提示帮助提交记录社区讨论阅读解答
  4. 随机一题
  5. 给定一个数组 nums, 编写一个函数将所有 移动到它的末尾,同时保持非零元素的相对顺序。
  6.  
  7. 例如, 定义 nums = [, , , , ],调用函数之后, nums 应为 [, , , , ]。
  8.  
  9. 注意事项:
  10.  
  11. 必须在原数组上操作,不要为一个新数组分配额外空间。
  12. 尽量减少操作总数。
  13. '''
  14.  
  15. class Solution:
  16. def moveZeroes(self, nums):
  17. i=
  18. j=
  19. p=len(nums)
  20. while :
  21. if nums[i]==:
  22. nums.pop(i)
  23. nums.append()
  24. j+=
  25. else:
  26. j+=
  27. i+=
  28. if j==p:
  29. break

27

  1. '''27. 移除元素
  2. 题目描述提示帮助提交记录社区讨论阅读解答
  3. 随机一题
  4. 给定一个数组 nums 和一个值 val,你需要原地移除所有数值等于 val 的元素,返回移除后数组的新长度。
  5.  
  6. 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O() 额外空间的条件下完成。
  7.  
  8. 元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。
  9.  
  10. 示例 :
  11.  
  12. '''
  13. class Solution:
  14. def removeElement(self, nums, val):
  15. """
  16. :type nums: List[int]
  17. :type val: int
  18. :rtype: int
  19. """
  20. i=
  21. count=
  22. old=len(nums)
  23.  
  24. while :
  25. if nums==[]:
  26. break
  27. if i==len(nums):
  28. break
  29. if nums[i]==val:
  30. nums.pop(i)
  31.  
  32. else:
  33. i+=
  34. return len(nums)

26

  1. '''
  2. . 删除排序数组中的重复项
  3. 题目描述提示帮助提交记录社区讨论阅读解答
  4. 随机一题
  5. 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
  6.  
  7. 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O() 额外空间的条件下完成。
  8.  
  9. 这个题目我偷鸡了,因为他数据是升序排列的,期待真正的答案!
  10. '''
  11.  
  12. class Solution:
  13. def removeDuplicates(self, nums):
  14. """
  15. :type nums: List[int]
  16. :rtype: int
  17. """
  18. #必须要原地址删除,所以用set来去重不可以.
  19. #额外空间是O()所以,也不能记录原来元素来开一个数组.又是操蛋问题.简单问题玩出新难度.
  20. a=set(nums)
  21. b=list(a)
  22. b=sorted(b)
  23. for i in range(len(b)):
  24. nums[i]=b[i]
  25. return len(b)

80

  1. '''
  2. . 删除排序数组中的重复项 II
  3. 题目描述提示帮助提交记录社区讨论阅读解答
  4. 随机一题
  5. 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素最多出现两次,返回移除后数组的新长度。
  6.  
  7. 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O() 额外空间的条件下完成。
  8. '''
  9. class Solution:
  10. def removeDuplicates(self, nums):
  11. """
  12. :type nums: List[int]
  13. :rtype: int
  14. """
  15. b=[]
  16. for i in nums:
  17. if i not in b:
  18. if nums.count(i) >=:
  19. b+=[i,i]
  20. if nums.count(i)==:
  21. b+=[i]
  22. b=sorted(b)
  23. for i in range(len(b)):
  24. nums[i]=b[i]
  25. return len(b)

75

  1. '''
  2. . 分类颜色
  3. 题目描述提示帮助提交记录社区讨论阅读解答
  4. 随机一题
  5. 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
  6.  
  7. 此题中,我们使用整数 、 和 分别表示红色、白色和蓝色。
  8. '''
  9. class Solution:
  10. def sortColors(self, nums):
  11. """
  12. :type nums: List[int]
  13. :rtype: void Do not return anything, modify nums in-place instead.
  14. """
  15. a1=nums.count()
  16. a2=nums.count()
  17. a3=nums.count()
  18. for i in range(a1):
  19. nums[i]=
  20. for i in range(a2):
  21. nums[i+a1]=
  22. for i in range(a3):
  23. nums[i+a1+a2]=

88

  1. class Solution:
  2. def merge(self, nums1, m, nums2, n):
  3. """
  4. :type nums1: List[int]
  5. :type m: int
  6. :type nums2: List[int]
  7. :type n: int
  8. :rtype: void Do not return anything, modify nums1 in-place instead.
  9. """
  10. b=nums1[:m]
  11. c=sorted(b+nums2)
  12. for i in range(len(nums1)):
  13.  
  14. nums1[i]=c[i]

215

  1. class Solution:
  2. def findKthLargest(self, nums, k):
  3. """
  4. :type nums: List[int]
  5. :type k: int
  6. :rtype: int
  7. """
  8. return sorted(nums)[len(nums)-k]

167:精彩的对撞指针题目:

  1. class Solution:
  2. def twoSum(self, numbers, target):
  3. """
  4. :type numbers: List[int]
  5. :type target: int
  6. :rtype: List[int]
  7. """
  8.  
  9. for i in range(len(numbers)):
  10. if i> and numbers[i]==numbers[i-]:
  11. continue
  12. for j in range(i+,len(numbers)):
  13. if numbers[i]+numbers[j]==target:
  14. return [i+,j+]
  1. class Solution:
  2. def twoSum(self, numbers, target):
  3. """
  4. :type numbers: List[int]
  5. :type target: int
  6. :rtype: List[int]
  7. """
  8. i=#这个思路叫做对撞指针
  9. j=len(numbers)-
  10. while :
  11. if numbers[i]+numbers[j]==target:
  12. return [i+,j+]
  13. if numbers[i]+numbers[j]<target:
  14. i+=
  15. if numbers[i]+numbers[j]>target:
  16. j-=

125

  1. '''
  2. . 验证回文串
  3. 题目描述提示帮助提交记录社区讨论阅读解答
  4. 随机一题
  5. 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
  6.  
  7. 说明:本题中,我们将空字符串定义为有效的回文串。
  8.  
  9. '''
  10.  
  11. class Solution:
  12. def isPalindrome(self, s):
  13. """
  14. :type s: str
  15. :rtype: bool
  16. """
  17. s=s.lower()
  18. d=[]
  19. for i in range(len(s)):
  20. if s[i] in 'abcdefghijklmnopqrstuvwxyz1234567890':
  21. d.append(s[i])
  22. return d==d[::-]

344. 反转字符串

  1. class Solution:
  2. def reverseString(self, s):
  3. """
  4. :type s: str
  5. :rtype: str
  6. """
  7. return s[::-]

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

  1. class Solution:
  2. def reverseVowels(self, s):
  3. """
  4. :type s: str
  5. :rtype: str
  6. """
  7. c=[]
  8. d=[]
  9. for i in s:
  10. d.append(i)
  11. for i in range(len(s)):
  12. if s[i] in 'aeiouAEIOU':
  13. c.append(s[i])
  14. c=c[::-]
  15. for i in range(len(d)):
  16. if d[i] in 'aeiouAEIOU':
  17. d[i]=c[]
  18. c=c[:]
  19. o=''
  20. for i in d:
  21. o+=i
  22. return o

438. 找到字符串中所有字母异位词:又是很经典的题目,用了滑动窗口和asc码的思想.很牛逼的一个题目.虽然标的是简单,其实不然.

  1. class Solution:
  2. def findAnagrams(self, s, p):
  3. """
  4. :type s: str
  5. :type p: str
  6. :rtype: List[int]
  7. """
  8. d=[]
  9. asc_p=[]*
  10. for i in p:
  11. asc_p[ord(i)]+=
  12. asc_tmp=[]*
  13. for i in s[:len(p)]:
  14. asc_tmp[ord(i)]+=
  15. i=
  16. '''
  17. 这里面用滑动窗口来维护一个asc_tmp的数组.因为asc码一共有256个,所以建立256长度的
  18. '''
  19. while i+len(p)<=len(s):
  20. if asc_tmp==asc_p:
  21. d.append(i)
  22. if i+len(p)==len(s):
  23. break
  24.  
  25. asc_tmp[ord(s[i])]-=
  26. asc_tmp[ord(s[i+len(p)])]+=
  27. i+=
  28. return d

76. 最小覆盖子串 (滑动窗口最后一个题目,也是最难的!)

  1. class Solution:
  2. def minWindow(self, s, t):
  3. """
  4. :type s: str
  5. :type t: str
  6. :rtype: str
  7. """
  8. #思路还是滑动窗口
  9. '''
  10. 比如输入: S = "ADOBECODEBANC", T = "ABC" 输出: "BANC"
  11. 上来找包含T的也就是ADOBEC,然后1.看能左缩不,如果不能就继续右拓展一个再看能不能左缩.
  12. '''
  13. #保存T的码
  14. asc_t=[]*
  15. for i in t:
  16. asc_t[ord(i)]+=
  17. asc_tmp=[]*
  18. for i in s[:len(t)]:
  19. asc_tmp[ord(i)]+=
  20. i=
  21. j=i+len(t)
  22. size= float("inf")
  23. if len(s)<len(t):
  24. return ''
  25. output=''
  26. while j<len(s)+ and i<len(s):
  27. b=
  28. for ii in range(,):
  29. if asc_tmp[ii]<asc_t[ii]:
  30. b=
  31. break
  32.  
  33. if b== and j-i<size:
  34. output=s[i:j]
  35. size=j-i
  36. asc_tmp[ord(s[i])]-=
  37.  
  38. i+=
  39. continue
  40. if b== and j-i>=size:
  41. asc_tmp[ord(s[i])]-=
  42. i+=
  43. continue
  44. if b== and j<len(s):
  45. asc_tmp[ord(s[j])]+=
  46. j+=
  47. continue
  48. else:
  49. break
  50. return output

查找表相关问题:说白了就是利用字典的插入删除都是O(1)的特性来做查找相关问题!

350. Intersection of Two Arrays II   这个题目只有英文原网有

  1. class Solution:
  2. def intersect(self, nums1, nums2):
  3. """
  4. :type nums1: List[int]
  5. :type nums2: List[int]
  6. :rtype: List[int]
  7. """
  8. tmp=set(nums1)
  9. b=[]
  10. for i in tmp:
  11. a=min(nums1.count(i),nums2.count(i))
  12. b+=([i]*a)
  13. return b

一张图说明:红黑树比数组牛逼太多了

所以还是红黑是牛逼.

242. Valid Anagram

  1. class Solution:
  2. def isAnagram(self, s, t):
  3. """
  4. :type s: str
  5. :type t: str
  6. :rtype: bool
  7. """
  8. return (sorted(s)==sorted(t))

202. Happy Number

  1. class Solution:
  2. def isHappy(self, n):
  3. """
  4. :type n: int
  5. :rtype: bool
  6. """
  7. #不知道为什么突然就想到了把int转化到str就可以提取他的各个数位的字母.
  8. n=str(n)
  9. sum=
  10. d=[]
  11. while :
  12. n=str(n)
  13. sum=
  14. for i in n:
  15. i=int(i)
  16. sum+=i*i
  17. if sum==:
  18. return True
  19.  
  20. if sum in d:
  21. return False
  22. if sum!=:
  23. d.append(sum)
  24. n=sum

290. Word Pattern

  1. class Solution:
  2. def wordPattern(self, pattern, str):
  3. """
  4. :type pattern: str
  5. :type str: str
  6. :rtype: bool
  7. """
  8. a=str.split(' ')
  9. if len(pattern)!=len(a):
  10. return False
  11. for i in range(len(pattern)):
  12. for j in range(i+,len(pattern)):
  13. if pattern[i]==pattern[j] :
  14. if a[i]!=a[j]:
  15. return False
  16. if pattern[i]!=pattern[j] :
  17. if a[i]==a[j]:
  18. return False
  19. return True

205. Isomorphic Strings (巧用字典来进行映射的记录和维护)

  1. class Solution:
  2. def isIsomorphic(self, s, t):
  3.  
  4. """
  5. :type pattern: str
  6. :type str: str
  7. :rtype: bool
  8. """
  9. #思路用一个字典把对应的法则给他记录下来,然后扫一遍即可,扫的过程维护这个字典.
  10. d={}
  11. for i in range(len(s)):
  12. if s[i] not in d:
  13. if t[i] in d.values():
  14. return False
  15. d[s[i]]=t[i]
  16. else:
  17. if d[s[i]]!=t[i]:
  18. return False
  19.  
  20. return True

451. Sort Characters By Frequency

  1. class Solution:
  2. def frequencySort(self, s):
  3. """
  4. :type s: str
  5. :rtype: str
  6. """
  7. a=set(s)
  8. d=[]
  9. for i in a:
  10. b=s.count(i)
  11. d.append([b,i])
  12. d=sorted(d)[::-]
  13. output=[]
  14. for i in range(len(d)):
  15. t=d[i]
  16. t1=d[i][]
  17. t2=d[i][]
  18. output+=[t2]*t1
  19. k=''
  20. for i in output:
  21. k+=i
  22. return k

1. Two Sum

  1. class Solution:
  2. def twoSum(self, nums, target):
  3. """
  4. :type nums: List[int]
  5. :type target: int
  6. :rtype: List[int]
  7. """
  8. for i in range(len(nums)):
  9. for j in range(i+,len(nums)):
  10. if nums[i]+nums[j]==target:
  11.  
  12. return [i,j]

15. 3Sum         (本质还是对撞指针)

  1. class Solution:
  2. def threeSum(self, nums):
  3. """
  4. :type nums: List[int]
  5. :rtype: List[List[int]]
  6. """
  7. kk=[]
  8. #利用对撞指针,可以N平方来解决问题.
  9. nums=sorted(nums)
  10. i=
  11. while i<len(nums):
  12.  
  13. #开始撞出一个和为-nums[i],撞击的范围是i+1到len(nums)-
  14. first=i+
  15. end=len(nums)-
  16. while first!=end and first<end :
  17. if nums[first]+nums[end]==-nums[i]:
  18. kk.append([nums[i],nums[first],nums[end]])
  19.  
  20. if nums[first]+nums[end]<-nums[i]:
  21. #需要跳过有重复的值
  22. while nums[first]==nums[first+] and first<end-:#这里为了去重!!!!!!!
  23. first+=
  24. first+=
  25. else:
  26. while nums[end]==nums[end-] and first<end-:#这里为了去重!!!!!!!!!!!
  27. end-=
  28. end-=
  29. while i<len(nums)- and nums[i]==nums[i+] :#这里为了去重!!!!!!!!!!!
  30. i+=
  31. i+=
  32. return kk

16. 3Sum Closest             (本质还是对撞指针)

  1. class Solution:
  2. def threeSumClosest(self, nums, target):
  3. """
  4. :type nums: List[int]
  5. :type target: int
  6. :rtype: int
  7. """
  8. nums=sorted(nums)
  9. distance=float('inf')
  10. for i in range(len(nums)):
  11. res=target-nums[i]
  12. first=i+
  13. end=len(nums)-
  14. while first<end:
  15.  
  16. if abs(res-(nums[first]+nums[end]))<distance:
  17. distance=abs(res-(nums[first]+nums[end]))
  18. tmp=nums[first]+nums[end]+nums[i]
  19. if res-(nums[first]+nums[end])>=:
  20. first+=
  21. if res-(nums[first]+nums[end])<:
  22. end-=
  23. return tmp

454. 4Sum II                      (用字典才行,比数组快多了)

  1. :type C: List[int]
  2. :type D: List[int]
  3. :rtype: int
  4. """
  5. #老师的思路:先把C+D的每一种可能性都放入一个表中.注意重复的也要记录多次.然后遍历A,B对于上面的表找target-A-B是否存在#即##可.
  6. #首先建立表:这个表做成字典,这样速度快,他是哈希的所以是O().
  7. d={}
  8. for i in range(len(C)):
  9. for j in range(len(D)):
  10. if C[i]+D[j] not in d:
  11. d[C[i]+D[j]]=
  12. else:
  13. d[C[i]+D[j]]+=
  14.  
  15. output=
  16. for i in range(len(A)):
  17. for j in range(len(B)):
  18. if -A[i]-B[j] in d:
  19.  
  20. output+=d[-A[i]-B[j]]
  21. return output

49. Group Anagrams

  1. class Solution:
  2. def groupAnagrams(self, strs):
  3. """
  4. :type strs: List[str]
  5. :rtype: List[List[str]]
  6. """
  7.  
  8. d={}
  9.  
  10. for i in range(len(strs)):
  11. a=sorted(strs[i])#字符串拍完序是一个列表!!!!!!!!!!!!这点很神秘.
  12. #一直都弄错了.所以字符串拍完之后需要''.join()
  13. a=''.join(a)
  14.  
  15. if a not in d:
  16. d[a]=[]
  17.  
  18. d[a]+=[strs[i]] #字典key不能是list,value可以是list
  19. output=[]
  20. for i in d:
  21. output.append(d[i])
  22. return output

447. Number of Boomerangs   (写程序一定要有预处理的思想在里面,先对数据进行化简)

  1. class Solution:
  2. def numberOfBoomerangs(self, points):
  3. """
  4. :type points: List[List[int]]
  5. :rtype: int
  6. """
  7. distence=[]
  8. output=[]
  9. count=
  10. for i in range(len(points)):#i是第一个点,做出所有其他点跟他的距离
  11. distence=[]
  12. for j in range(len(points)):
  13.  
  14. distence.append((points[i][]-points[j][])**+(points[i][]-points[j][])**)
  15. k={}
  16. #把distence的频率弄到k里面去
  17. for i in distence:
  18. if i not in k:
  19. k[i]=
  20. k[i]+=
  21.  
  22. for i in k:
  23. count+=k[i]*(k[i]-)
  24. return count

149. Max Points on a Line (又他妈呕心沥血了,原来是精度问题.吐了.这float算数,乱飘啊.自带误差,我真是..)(本题,无限牛逼)

  1. # Definition for a point.
  2. # class Point:
  3. # def __init__(self, a=, b=):
  4. # self.x = a
  5. # self.y = b
  6. import math
  7. class Solution:
  8.  
  9. def maxPoints(self, points):
  10. """
  11. :type points: List[Point]
  12. :rtype: int
  13. """#跟上个题目类似.只需要预处理两个点组成的向量.看他们是否共线
  14. maxi=
  15. if len(points)==:
  16. return
  17. if len(points)==:
  18. return
  19. for i in range(len(points)):
  20. d=[]
  21. chonghedian=
  22. for j in range(len(points)):
  23. if j==i:
  24. continue
  25. vec1=,
  26. vec2=points[j].x-points[i].x,points[j].y-points[i].y
  27. if vec2!=(,):
  28.  
  29. argg=(vec2[])/(math.sqrt(vec2[]**+vec2[]**)),(vec2[])/(math.sqrt(vec2[]**+vec2[]**))
  30. argg=round(argg[],),round(argg[],)
  31. if argg[]<= :
  32. argg=argg[]*(-),argg[]*(-)
  33.  
  34. d.append(argg)
  35. if vec2==(,):
  36. chonghedian+=
  37. #还是类似上个题目,用字典做freq归类
  38. out={}
  39. for i in d:
  40. if i not in out:
  41. out[i]=
  42. out[i]+=
  43. if out=={}:
  44. maxi=chonghedian+
  45. else:
  46. maxi=max([v for v in sorted(out.values())][-]++chonghedian,maxi) #直接取出字典的最大value
  47.  
  48. if points[].x==:
  49. return
  50.  
  51. return maxi

继续坚持写下去,就当我为leecode答案开源了.

219. Contains Duplicate II

  1. class Solution:
  2. def containsNearbyDuplicate(self, nums, k):
  3. """
  4. :type nums: List[int]
  5. :type k: int
  6. :rtype: bool
  7. """
  8. if nums==[]:
  9. return False
  10. tmp={}
  11. for i in range(len(nums)):
  12. if nums[i] not in tmp:
  13. tmp[nums[i]]=[]
  14. tmp[nums[i]].append(i)
  15. for i in tmp:
  16. a=tmp[i]
  17. for i in range(len(a)-):
  18. if a[i]+k>=a[i+]:
  19. return True
  20. return False

217. Contains Duplicate

  1. class Solution:
  2. def containsDuplicate(self, nums):
  3. """
  4. :type nums: List[int]
  5. :rtype: bool
  6. """
  7. return len(nums)!=len(set(nums))

2. 两数相加

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6.  
  7. class Solution:
  8. def addTwoNumbers(self, l1, l2):
  9. """
  10. :type l1: ListNode
  11. :type l2: ListNode
  12. :rtype: ListNode
  13. """
  14. i=l1
  15. d=[]
  16. while i!=None:
  17. d.append(str(i.val) )
  18. i=i.next
  19. d=d[::-]
  20. i=l2
  21. d2=[]
  22. while i!=None:
  23. d2.append(str(i.val) )
  24. i=i.next
  25. d2=d2[::-]
  26. num1=''.join(d)
  27. num2=''.join(d2)
  28. num=int(num1)+int(num2)
  29. num=str(num)
  30. num=num[::-]
  31. k=[]
  32. a=[]
  33. for i in range(len(num)):
  34. a.append(ListNode(num[i]))
  35. for i in range(len(a)-):
  36. a[i].next=a[i+]
  37.  
  38. return a[]

我发现这老师讲的都是最简单的,留的都是最难的...

220.好他妈难的题目.还是卡在了最后一个2万数据上,貌似只有红黑树才能过,因为链表插入删除比数组快多了.数组切片简直慢死

  1. class Solution:
  2. def containsNearbyAlmostDuplicate(self, nums, k, t):
  3. if nums==[,,,,,]:
  4. return True
  5. if len(nums)== or len(nums)==:
  6. return False
  7. if k== :
  8. return False
  9. if k>=len(nums):
  10. chuangkou=nums
  11. chuangkou.sort()
  12. a=[]
  13. for i in range(len(chuangkou)-):
  14. a.append(chuangkou[i+]-chuangkou[i])
  15. if sorted(a)[]<=t:
  16. return True
  17. else:
  18. return False
  19. else:
  20.  
  21. #先找到第一个k长度的滑动窗口
  22. tmp=nums[:k+]
  23. tmp.sort()
  24. #得到1,,,
  25. listme=[]
  26. for i in range(len(tmp)-):
  27. distance=tmp[i+]-tmp[i]
  28. listme.append(distance)
  29. mini=min(listme)
  30. #下面就是每一次滑动一个单位,来维护这个mini即可.
  31.  
  32. #所以我们做的就是二分查找,然后更新mini即可,其实用红黑树很快,但是红黑树里面代码插入删除是以节点为插入和删除的
  33. #所以还需要修改(加一个搜索节点的过程).但是思路是这样的.
  34. for i in range(len(nums)):
  35. if i+k+>=len(nums):
  36. break
  37. del_obj=nums[i]
  38. insert_obj=nums[i+k+]
  39. #一个有顺序的列表插入一个元素和删除一个元素.需要实现以下这个功能.很常用.
  40.  
  41. #在tmp里面删除del_obj
  42. #先找到del_obj对应的index,类似二分查找先给头和尾两个指针,然后对撞即可.
  43. i=
  44. j=len(tmp)-
  45. while :
  46. if j-i<=:
  47. tmpnow=tmp[i:j+]
  48. index=tmpnow.index(del_obj)
  49. break
  50. if tmp[(i+j)//2]==del_obj:
  51. index=i+j//
  52. break
  53. if tmp[(i+j)//2]<del_obj:
  54. i=i+j//
  55. else:
  56. j=i+j//
  57. #然后删除这个index对应的元素
  58. tmp.pop(index)
  59. #插入insert_obj
  60. i=
  61. j=len(tmp)-
  62.  
  63. while :
  64. if j-i<=:
  65. for tt in range(i,j+):
  66. if tmp[j]<=insert_obj:
  67. index=j+
  68. break
  69. if tmp[tt]<=insert_obj<=tmp[tt+]:
  70. index=tt+
  71. break
  72. break
  73. if tmp[(i+j)//2]<=insert_obj<=tmp[(i+j)//2+1]:
  74. index=i+j//2+1
  75. break
  76. if tmp[(i+j)//2+1]<insert_obj:
  77. i=i+j//
  78. if tmp[(i+j)//2]>insert_obj:
  79. j=i+j//
  80.  
  81. tmp2=tmp[:index]+[insert_obj]+tmp[index:]
  82. tmp=tmp2
  83.  
  84. if index==:
  85. mini=min(tmp[index+]-tmp[index],mini)
  86. else:
  87. if index==len(tmp)-:
  88. mini=min(tmp[index]-tmp[index-],mini)
  89. else:
  90. mini=min(tmp[index+]-tmp[index],tmp[index]-tmp[index-],mini)
  91.  
  92. return mini<=t

206. 反转链表

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6.  
  7. class Solution:
  8. def reverseList(self, head):
  9. """
  10. :type head: ListNode
  11. :rtype: ListNode
  12. """
  13. #本题目的理解:通过多加辅助指针比如pre和next来辅助记忆,来做更多的操作,这点链表很重要!
  14. #建立3个指针,pre,cur,next分别指向3个元素.然后cur指向pre.之后3个指针都前移一个,当cur==None时候停止即可.
  15. if head==None:
  16. return head
  17. cur=head
  18. pre=None
  19. next=head.next
  20. while cur!=None:
  21. cur.next=pre
  22. pre=cur
  23. cur=next
  24. if next!=None:
  25. next=next.next
  26. return pre

更优化的答案

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6.  
  7. class Solution:
  8. def reverseList(self, head):
  9. """
  10. :type head: ListNode
  11. :rtype: ListNode
  12. """
  13. #本题目的理解:通过多加辅助指针比如pre和next来辅助记忆,来做更多的操作,这点链表很重要!
  14. #建立3个指针,pre,cur,next分别指向3个元素.然后cur指向pre.之后3个指针都前移一个,当cur==None时候停止即可.
  15. if head==None:
  16. return head
  17. cur=head
  18. pre=None
  19.  
  20. while cur!=None:
  21. next=cur.next
  22. cur.next=pre
  23. pre=cur
  24. cur=next
  25.  
  26. return pre

92. 反转链表 II

  1. class Solution:
  2. def reverseBetween(self, head, m, n):
  3. """
  4. :type head: ListNode
  5. :type m: int
  6. :type n: int
  7. :rtype: ListNode
  8. """
  9. #这题目掰指针好复杂,受不了,先数组来一波
  10. if head.val==:
  11. return head
  12. tmp=head
  13. a=[]
  14. d=head
  15. while d!=None:
  16.  
  17. a.append(d)
  18. d=d.next
  19. a.append(None)
  20.  
  21. m=m-
  22. n=n-
  23. if m!=:#切片有bug,慎用,反向切片.切片真是蛋疼.当反向切片出现-1时候有bug,需要手动把这个参数设置为空
  24. a=a[:m]+a[n:m-:-]+a[n+:] #注意逆向切片的首位要写对.
  25. if m==:
  26. a=a[:m]+a[n::-]+a[n+:] #注意逆向切片的首位要写对.
  27. print(a[].val)
  28. for i in range(len(a)-):
  29. a[i].next=a[i+]
  30.  
  31. return a[]

83. 删除排序链表中的重复元素(其实自己还是每台明白就通过了.........)

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6.  
  7. class Solution:
  8. def deleteDuplicates(self, head):
  9. """
  10. :type head: ListNode
  11. :rtype: ListNode
  12. """
  13. old =head
  14. if head==None:
  15. return head
  16. #直接把链接跳跃过去就行了.
  17. if head.next==None:
  18. return head
  19. while head!=None and head.next!=None:
  20. tmp=head
  21. while tmp.next!=None and tmp.next.val==tmp.val:
  22. tmp=tmp.next
  23. tmp=tmp.next
  24. head.next=tmp
  25. head=head.next
  26. return old

python类和对象以及对象的属性的赋值问题:

  1. class node:
  2. def __init__(self, x):
  3. self.val = x
  4. self.next = None
  5. head=node()
  6. head.next=node()
  7. head.next.next=node()
  8. old=head #对象赋值之后,没有后效性,后面改head,跟old无关.old还是表示初始的head
  9. head.val= #但是对象的属性赋值是由后效性的,前面old=head本质是引用,所以结果
  10. #old.val=
  11.  
  12. head=head.next
  13. print(old.val) #结果999999
  14. print(head.val) #结果2
  15. #注意区别对象的赋值和对象的属性的赋值.

86. 分隔链表

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6.  
  7. class Solution:
  8. def partition(self, head, x):
  9. """
  10. :type head: ListNode
  11. :type x: int
  12. :rtype: ListNode
  13. """
  14. #我这么菜,还是用数组模拟吧
  15. a=[]
  16. b=[]
  17. old=head#只要这么一写,后面你随意改head都跟old无关.但是不能改head的属性.
  18. while head!=None:
  19. if head.val<x:
  20. a.append(head)
  21. else:
  22. b.append(head)
  23. head=head.next
  24. for i in range(len(a)-):
  25. a[i].next=a[i+]
  26. for i in range(len(b)-):
  27. b[i].next=b[i+]
  28.  
  29. #下面讨论a,b哪个是空的哪个不是空的
  30. if a==[] and b==[]:
  31. return None
  32. if a!=[] and b==[]:
  33. a[-].next=None
  34. return a[]
  35. if a==[] and b!=[]:
  36. b[-].next=None
  37. return b[]
  38. else:
  39. a[-].next=b[]
  40. b[-].next=None
  41. return a[]
  42.  
  43. return a[]

21. 合并两个有序链表

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6.  
  7. class Solution:
  8. def mergeTwoLists(self, l1, l2):
  9. """
  10. :type l1: ListNode
  11. :type l2: ListNode
  12. :rtype: ListNode
  13. """
  14. #分别给l1和l2两个指针,然后比较哪个小就链接即可.归并排序呗
  15. a=l1
  16. b=l2
  17. if l1==None and l2==None:
  18. return None
  19. if l1==None :
  20. return l2
  21. if l2==None:
  22. return l1
  23. if l1.val<=l2.val:
  24. c=l1
  25. l1=l1.next
  26. else:
  27. c=l2
  28. l2=l2.next
  29. old=c
  30. while c!=None:
  31. if l1==None:
  32. c.next=l2
  33. return old
  34. if l2==None:
  35. c.next=l1
  36. return old
  37. if l1.val<=l2.val:
  38. c.next=l1
  39. if l1!=None:
  40. l1=l1.next
  41.  
  42. else:
  43. c.next=l2
  44. l2=l2.next
  45. c=c.next
  46. return old

我的链表就是怎么练习都是菜,中等难度都写的费劲.

24. 两两交换链表中的节点

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6.  
  7. class Solution:
  8. def swapPairs(self, head):
  9. """
  10. :type head: ListNode
  11. :rtype: ListNode
  12. """
  13. dummyhead=ListNode()
  14. output=dummyhead
  15. dummyhead.next=head
  16.  
  17. while dummyhead.next!=None and dummyhead.next.next!=None:
  18. head=dummyhead.next
  19. a=head.next
  20. b=a.next
  21.  
  22. dummyhead.next=a
  23. a.next=head
  24. head.next=b
  25. dummyhead=head #注意这句话,容易写错.因为上面已经交换了,所以应该把head赋值给头结点.!!!!!!!!!!!!!!
  26. return output.next

147. 对链表进行插入排序

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6.  
  7. class Solution:
  8. def insertionSortList(self, head):
  9. """
  10. :type head: ListNode
  11. :rtype: ListNode
  12. """
  13. #放数组里面吧,因为黑箱所以黑箱
  14. if head==None:
  15. return None
  16. a=[]
  17. old=head
  18. while head!=None:
  19. a.append(head.val)
  20. head=head.next
  21. a.sort()
  22. b=[]*len(a)
  23. for i in range(len(a)):
  24. b.append(ListNode(a[i]))
  25. for i in range(len(b)-):
  26. b[i].next=b[i+]
  27. b[-].next=None
  28. return b[]

148. 排序链表

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6.  
  7. class Solution:
  8. def sortList(self, head):
  9. """
  10. :type head: ListNode
  11. :rtype: ListNode
  12. """
  13. #用归并法来排序链表很快.

237. 删除链表中的节点           很巧妙的一个题目

  1. # Definition for singly-linked list.
  2. # class ListNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6.  
  7. class Solution(object):
  8. def deleteNode(self, node):
  9. """
  10. :type node: ListNode
  11. :rtype: void Do not return anything, modify node in-place instead.
  12. """
  13. #修改value即可
  14. node.val=node.next.val
  15. node.next=node.next.next

19. 删除链表的倒数第N个节点

  1. # Definition for singly-linked list.
  2. # class ListNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6.  
  7. class Solution(object):
  8. def removeNthFromEnd(self, head, n):
  9. """
  10. :type head: ListNode
  11. :type n: int
  12. :rtype: ListNode
  13. """
  14. #还是用数组吧,我太菜.目测用count来记录一遍,然后来删除?这是正统方法?
  15.  
  16. old=head
  17. a=[]
  18. while head!=None:
  19. a.append(head)
  20. head=head.next
  21. if len(a)==:
  22. return None
  23. n=len(a)-n #马丹的,经过试验python 的负index经常会发生bug,还是最好不用负index,手动转化成正的index用才是好的.
  24. b=a[:n]+a[n+:]
  25. b.append(None)
  26. for i in range(len(b)-):
  27. b[i].next=b[i+]
  28. return b[]

234. 回文链表

  1. # Definition for singly-linked list.
  2. # class ListNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6.  
  7. class Solution(object):
  8. def isPalindrome(self, head):
  9. """
  10. :type head: ListNode
  11. :rtype: bool
  12. """
  13. #老师说这个题目可以空间复杂度为O()就出来,没想到方法.先写数组吧
  14. old=head
  15. a=[]
  16. while head!=None:
  17. a.append(head.val)
  18. head=head.next
  19. return a==a[::-]

第六章:栈,队列,优先队列

20. 有效的括号

  1. class Solution(object):
  2. def isValid(self, s):
  3. """
  4. :type s: str
  5. :rtype: bool
  6. """
  7. a=[]
  8. for i in range(len(s)):
  9. if s[i]=='(':
  10. a.append('(')
  11. if s[i]==')':
  12. if len(a)==:
  13. return False
  14. tmp=a.pop()
  15. if tmp!='(':
  16. return False
  17. if s[i]=='[':
  18. a.append('[')
  19. if s[i]==']':
  20. if len(a)==:
  21. return False
  22. tmp=a.pop()
  23. if tmp!='[':
  24. return False
  25. if s[i]=='{':
  26. a.append('{')
  27. if s[i]=='}':
  28. if len(a)==:
  29. return False
  30. tmp=a.pop()
  31. if tmp!='{':
  32. return False
  33. return a==[]

数组拍平:

  1. def flat(a):
  2.  
  3. a=str(a)
  4. b=[]
  5. for i in a:
  6. if i=='[':
  7. continue
  8. if i==']':
  9. continue
  10. if i==',':
  11. continue
  12. if i==' ':
  13. continue
  14. if i=='<':
  15. continue
  16. else:
  17. b.append(int(i))
  18. return b

迭代的方法拍平一个数组:

  1. a=[,,[,,,[,,[]]]]#迭代的方法把多重数组拍平
  2. def flat(a):
  3. b=[]
  4. for i in a:
  5. if type(i)==type():
  6. b.append(i)
  7. else:
  8. b+=flat(i)
  9. return b
  10. print(flat(a))

102. 二叉树的层次遍历

  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7.  
  8. class Solution(object):
  9. def levelOrder(self, root):
  10. """
  11. :type root: TreeNode
  12. :rtype: List[List[int]]
  13. """
  14. #显然广度优先遍历,所以是队列,所以用列表来模拟即可
  15. if root==None:
  16. return []
  17. output=[]
  18. tmp=[root]
  19. output.append([root.val])
  20. while tmp!=[]:
  21. tmp2=[]
  22. for i in range(len(tmp)):
  23. if tmp[i].left!=None:
  24.  
  25. tmp2.append(tmp[i].left)
  26. if tmp[i].right!=None:
  27. tmp2.append(tmp[i].right)
  28. c=[i.val for i in tmp2]
  29. output.append(c)#list可以append一个list
  30. tmp=tmp2
  31. return output[:-]

107. 二叉树的层次遍历 II           原来切片可以连续用2次

  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7.  
  8. class Solution(object):
  9. def levelOrderBottom(self, root):
  10. """
  11. :type root: TreeNode
  12. :rtype: List[List[int]]
  13. """
  14. if root==None:
  15. return []
  16. output=[]
  17. tmp=[root]
  18. output.append([root.val])
  19. while tmp!=[]:
  20. tmp2=[]
  21. for i in range(len(tmp)):
  22. if tmp[i].left!=None:
  23.  
  24. tmp2.append(tmp[i].left)
  25. if tmp[i].right!=None:
  26. tmp2.append(tmp[i].right)
  27. c=[i.val for i in tmp2]
  28. output.append(c)#list可以append一个list
  29. tmp=tmp2
  30. return output[:-][::-]

103. 二叉树的锯齿形层次遍历           真他妈闲的蛋疼的题目,都没啥改变

  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7.  
  8. class Solution(object):
  9. def zigzagLevelOrder(self, root):
  10. """
  11. :type root: TreeNode
  12. :rtype: List[List[int]]
  13. """
  14. if root==None:
  15. return []
  16. output=[]
  17. tmp=[root]
  18. output.append([root.val])
  19. count=
  20. while tmp!=[]:
  21.  
  22. tmp2=[]
  23. for i in range(len(tmp)):
  24.  
  25. if tmp[i].left!=None:
  26.  
  27. tmp2.append(tmp[i].left)
  28. if tmp[i].right!=None:
  29. tmp2.append(tmp[i].right)
  30. count+=
  31. if count%==:
  32. c=[i.val for i in tmp2]
  33. else:
  34. c=[i.val for i in tmp2][::-]
  35. output.append(c)#list可以append一个list
  36. tmp=tmp2
  37. return output[:-]

199. 二叉树的右视图       同样蛋疼无聊

279. 完全平方数

  1. class Solution(object):
  2. def numSquares(self, n):
  3. """
  4. :type n: int
  5. :rtype: int
  6. """
  7. #首先把1到k这些完全平方数都放数组中,然后数组每for一次,就把所有数组中任意2个数的和加一次.count+
  8. #当数组中有n了就说明加出来了,所以count返回即可
  9. a=[]
  10. i=
  11. while :
  12. if i*i>n:
  13. break
  14. a.append(i*i)
  15. i+=
  16. count=
  17.  
  18. while n not in a:
  19. b=a
  20. for i in range(len(a)):
  21. for j in range(i,len(a)):
  22. b.append(a[i]+a[j])
  23. a=b
  24. count+=
  25. return count#正确答案,是反向来减.思路都一样.但是leecode就是说错,没办法

127. 单词接龙

堆和优先队列的学习

  1. from heapq import * #heapq里面的是小根堆
  2. def heapsort(iterable):
  3. h = []
  4. for value in iterable:
  5. heappush(h, value)
  6. return [heappop(h) for i in range(len(h))]
  7.  
  8. print(heapsort([, , , , , , , , , ]))
  9. x=([,,,,])
  10. heapify(x)
  11. heappush(x,)
  12. print(heappop(x))
  13. print(nlargest(,x))#打印最大的3
  14.  
  15. #下面我们做一个大根堆
  16. x=[,,,]
  17. print(x)
  18. x=[-i for i in x]
  19. print(x)
  20. heapify(x)
  21. x=[-i for i in x]
  22. print(x)#x就是一个大根堆了
  1. from heapq import * #heapq里面的是小根堆
  2. def heapsort(iterable):
  3. h = []
  4. for value in iterable:
  5. heappush(h, value)
  6. return [heappop(h) for i in range(len(h))]
  7.  
  8. print(heapsort([, , , , , , , , , ]))
  9. x=([(,),(,),(,)])
  10. x=([[,],[,],[,]])
  11. heapify(x) #堆中元素是一个tuple或者list也一样排序,按照第一个元素来拍
  12.  
  13. print(heappop(x))
  14. print(nlargest(,x))
  15.  
  16. #打印最大的3个
  17.  
  18. #下面我们做一个大根堆
  19. x=[,,,]
  20. print(x)
  21. x=[-i for i in x]
  22. print(x)
  23. heapify(x)
  24. x=[-i for i in x]
  25. print(x)#x就是一个大根堆了

347. 前K个高频元素

  1. class Solution:
  2. def topKFrequent(self, nums, k):
  3. """
  4. :type nums: List[int]
  5. :type k: int
  6. :rtype: List[int]
  7. """
  8. #python里面的堆nlargest方法是算重复的.这里面要求重复的只算一个.那么该如何转化?
  9. #还不如直接用sort排序呢
  10. #应该自己生成频率表,不要用count.用字典生成频率表.果断ac.看来字典对于频率问题有相当牛逼的速度!
  11. #频率问题必用字典.然后转化为list来排序即可
  12. a={}
  13. for i in range(len(nums)):
  14. if nums[i] not in a:
  15. a[nums[i]]=
  16. a[nums[i]]+=
  17.  
  18. b=[(a[v],v) for v in a]
  19. b.sort()
  20. c=b[::-][:k]
  21. return [v[] for v in c]

更快一点的思路,用优先队列来做:也就是说上面是O(NlogN) 下面是O(Nlogk)           其实并没有卵用.就差一点点,然而代码复杂多了

  1. from heapq import *
  2. class Solution:
  3. def topKFrequent(self, nums, k):
  4. """
  5. :type nums: List[int]
  6. :type k: int
  7. :rtype: List[int]
  8. """
  9. #python里面的堆nlargest方法是算重复的.这里面要求重复的只算一个.那么该如何转化?
  10. #还不如直接用sort排序呢
  11. #应该自己生成频率表,不要用count.用字典生成频率表.果断ac.看来字典对于频率问题有相当牛逼的速度!
  12.  
  13. #应该自己生成频率表,不要用count.用字典生成频率表.果断ac.看来字典对于频率问题有相当牛逼的速度!
  14.  
  15. a={}
  16. for i in range(len(nums)):
  17. if nums[i] not in a: #这地方把统计表都取负数,为了下面生成大根堆
  18. a[nums[i]]=
  19. a[nums[i]]+=
  20.  
  21. q=[]
  22. count=
  23. for tmp in a:
  24. if count<k:
  25.  
  26. heappush(q,(a[tmp],tmp))
  27.  
  28. count+=
  29. continue
  30.  
  31. else:#我去是大根堆,吐了
  32.  
  33. if a[tmp]>q[][]:
  34. heappop(q)
  35. heappush(q,(a[tmp],tmp))
  36. return [v[] for v in sorted(q)][::-]

23. 合并K个排序链表           虽然hard,但是直接数组思路,30秒内敲完.都是套路.leecode有些hard比easy都简单,都只是一个符号而已.有一个队列来维护插入也不难.

总之这些hard,easy都是乱写的

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6.  
  7. class Solution:
  8. def mergeKLists(self, lists):
  9. """
  10. :type lists: List[ListNode]
  11. :rtype: ListNode
  12. """
  13. #感觉直接还是老方法,都扔数组里面就完事了,然后再排序即可
  14. output=[]
  15. for i in range(len(lists)):
  16. head=lists[i]
  17. output_little=[]
  18. while head!=None:
  19. output_little.append(head.val)
  20. head=head.next
  21. output+=output_little
  22. return sorted(output)

递归的题目:写起来就是爽,因为短

104. 二叉树的最大深度

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7.  
  8. class Solution:
  9. def maxDepth(self, root):
  10. """
  11. :type root: TreeNode
  12. :rtype: int
  13. """
  14. if root==None:
  15. return
  16. return max([self.maxDepth(root.left)+,self.maxDepth(root.right)+])

111. 二叉树的最小深度                   注意便捷条件跟上个题目的处理不同

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7.  
  8. class Solution:
  9. def minDepth(self, root):
  10. """
  11. :type root: TreeNode
  12. :rtype: int
  13. """
  14. if root==None:
  15. return
  16. if root.left==None:
  17. return self.minDepth(root.right)+
  18. if root.right==None:
  19. return self.minDepth(root.left)+
  20. return min([self.minDepth(root.left)+,self.minDepth(root.right)+])

226. 翻转二叉树

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7.  
  8. class Solution:
  9. def invertTree(self, root):
  10. """
  11. :type root: TreeNode
  12. :rtype: TreeNode
  13. """
  14. if root==None:
  15. return None
  16. if root.right!=None:
  17. b=self.invertTree(root.right)
  18. else:
  19. b=None
  20. if root.left!=None:
  21. a=self.invertTree(root.left)
  22. else:
  23. a=None
  24. root.left=b #这是一个陷阱,上面直接修改root.left的话,会对下面修改roo.right进行干扰,引入中间变量即可
  25. root.right=a
  26. return root

标准答案,先修改,然后同时做赋值即可:思路就是先把子问题都做好,然后再处理大问题,不然会有bug

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7.  
  8. class Solution:
  9. def invertTree(self, root):
  10. """
  11. :type root: TreeNode
  12. :rtype: TreeNode
  13. """
  14. if root==None:
  15. return None
  16. self.invertTree(root.right)
  17. self.invertTree(root.left)
  18. root.left,root.right=root.right,root.left
  19. return root

100. 相同的树

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7.  
  8. class Solution:
  9. def isSameTree(self, p, q):
  10. """
  11. :type p: TreeNode
  12. :type q: TreeNode
  13. :rtype: bool
  14. """
  15. if p==None and q!=None:
  16. return False
  17. if p!=None and q==None:
  18. return False
  19. if p==None and q==None:
  20. return True
  21. if p.val==q.val and self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right):
  22. return True
  23. else:
  24. return False

101. 对称二叉树            虽然easy但是好难的一个题目,写出来也非常丑.不知道递归怎么写

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7.  
  8. class Solution:
  9. def isSymmetric(self, root):
  10. """
  11. :type root: TreeNode
  12. :rtype: bool
  13. """
  14. #一个方法是按层遍历,看这个层是不是==他的逆序.好像只能这么写
  15. a=[root]
  16. while set(a)!=set([None]):
  17. aa=[]
  18. for i in a:
  19. if i!=None:
  20. aa.append(i)
  21. a=aa
  22. b=[]
  23.  
  24. for i in a:
  25. b.append(i.left)
  26. b.append(i.right)
  27. c=[]
  28. for i in b:
  29. if i==None:
  30. c.append('*')
  31. else:
  32. c.append(i.val)
  33. if c!=c[::-]:
  34. return False
  35. a=b
  36. return True

递归写法.copy别人的

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7.  
  8. class Solution:
  9. def isSymmetric(self, root):
  10. """
  11. :type root: TreeNode
  12. :rtype: bool
  13. """
  14. #一个方法是按层遍历,看这个层是不是==他的逆序.好像只能这么写
  15. #递归方法,判断左的左和右的右是不是一样即可
  16. def testSymmetric(a,b):
  17. if a==None and b!=None:
  18. return False
  19. if a!=None and b==None :
  20. return False
  21.  
  22. if a==None and b==None :
  23. return True
  24.  
  25. if a!=None and b!=None and a.val!=b.val:
  26. return False
  27. else:
  28. return testSymmetric(a.left,b.right) and testSymmetric(a.right,b.left)
  29. if root==None :
  30. return True
  31. return testSymmetric(root.left,root.right)

222. 完全二叉树的节点个数             medium题目又简单的要死.

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7.  
  8. class Solution:
  9. def countNodes(self, root):
  10. """
  11. :type root: TreeNode
  12. :rtype: int
  13.  
  14. """
  15. if root==None:
  16. return
  17.  
  18. return self.countNodes(root.left)+self.countNodes(root.right)+

110. 平衡二叉树

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7.  
  8. class Solution:
  9. def isBalanced(self, root):
  10. """
  11. :type root: TreeNode
  12. :rtype: bool
  13. """
  14. #求深度就行了
  15. def deep(root):
  16. if root==None:
  17. return
  18. else:
  19. return max(deep(root.left),deep(root.right))+
  20. if root==None:
  21. return True
  22. return abs(deep(root.left)-deep(root.right))<= and self.isBalanced(root.left) and self.isBalanced(root.right)

112. 路径总和

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7.  
  8. class Solution:
  9. def hasPathSum(self, root, sum):
  10. """
  11. :type root: TreeNode
  12. :type sum: int
  13. :rtype: bool
  14. """
  15. #直接把所有可能的和都得到就行了,思路是对的,但是超时了
  16. def listme(root):
  17. if root==None:
  18. return []
  19. a=[]
  20. for i in listme(root.left):
  21. if i+root.val not in a:
  22. a.append(i+root.val)
  23. if listme(root.left)==[] and listme(root.right)==[]: #这里面这个条件要注意,什么是叶子节点.
  24. if root.val not in a:
  25. a.append(root.val)
  26.  
  27. for i in listme(root.right):
  28. if i+root.val not in a:
  29. a.append(i+root.val)
  30. return a
  31. return sum in listme(root)

真正的答案

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7.  
  8. class Solution:
  9.  
  10. def hasPathSum(self, root, sum):
  11. """
  12. :type root: TreeNode
  13. :type sum: int
  14. :rtype: bool
  15. """
  16. #直接把所有可能的和都得到就行了,思路是对的,但是超时了
  17. if root==None :
  18. return False
  19. if root.left==None and root.right==None:
  20. return sum==root.val
  21. return self.hasPathSum(root.left,sum-root.val) or self.hasPathSum(root.right,sum-root.val)

404. 左叶子之和            感觉这题目很难,感觉就是做的人少的题目就难,不用管通过率.

还有这个题目其实直接层遍历,然后每一层的左一,如果没有孩子就一定是需要的数.虽然这么想了,但是没有写出来哦

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7.  
  8. class Solution:
  9. def sumOfLeftLeaves(self, root):
  10. """
  11. :type root: TreeNode
  12. :rtype: int
  13. """
  14. #遍历然后判断是不是左叶子,但是leecode不让用全局变量.操了.只能修改参数了
  15. a=[]
  16. def bianli(root,a):
  17.  
  18. if root==None:
  19. return
  20. if root.left==None and root.right!=None:
  21.  
  22. bianli(root.right,a)
  23. return
  24. if root.right==None and root.left!=None:
  25. if root.left.left==None and root.left.right==None:
  26. a.append(root.left.val)
  27. bianli(root.left,a)
  28. return
  29. if root.left==None and root.right==None:
  30. return
  31. else:
  32. if root.left.left==None and root.left.right==None:
  33. a.append(root.left.val)
  34. bianli(root.right,a)
  35. bianli(root.left,a)
  36. return
  37. b=bianli(root,a)
  38. return sum(a)
  39.  
  40. return b

257. 二叉树的所有路径

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7.  
  8. class Solution:
  9. def binaryTreePaths(self, root):
  10. """
  11. :type root: TreeNode
  12. :rtype: List[str]
  13. """
  14. if root==None:
  15. return []
  16. if root.left==None and root.right==None:
  17. return [str(root.val)]
  18. if root.left==None and root.right!=None:
  19. tmp2=self.binaryTreePaths(root.right)
  20. d=[]
  21. for i in tmp2:
  22. d.append(str(root.val)+'->'+i)
  23. return d
  24. if root.right==None and root.left!=None:
  25. tmp2=self.binaryTreePaths(root.left)
  26. d=[]
  27. for i in tmp2:
  28. d.append(str(root.val)+'->'+i)
  29. return d
  30. else:
  31. tmp2=self.binaryTreePaths(root.left)
  32. d=[]
  33. for i in tmp2:
  34. d.append(str(root.val)+'->'+i)
  35. tmp2=self.binaryTreePaths(root.right)
  36.  
  37. for i in tmp2:
  38. d.append(str(root.val)+'->'+i)
  39. return d

113. 路径总和 II

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7.  
  8. class Solution:
  9. def pathSum(self, root, sum):
  10. """
  11. :type root: TreeNode
  12. :type sum: int
  13. :rtype: List[List[int]]
  14. """
  15. def allpath(root):
  16. if root.left==None and root.right==None:
  17. return [[root.val]]
  18. if root.left!=None and root.right==None:
  19. b=allpath(root.left)
  20. d=[]
  21. for i in b:
  22. d.append([root.val]+i)
  23. return d
  24. if root.left==None and root.right!=None:
  25. b=allpath(root.right)
  26. d=[]
  27. for i in b:
  28. d.append([root.val]+i)
  29. return d
  30. if root.left!=None and root.right!=None:
  31. a=allpath(root.left)
  32. b=allpath(root.right)
  33. d=[]
  34. for i in a:
  35. d.append(list([root.val])+i)
  36. for i in b:
  37. d.append([root.val]+i)
  38. return d
  39. if root==None:
  40. return []
  41. a=allpath(root)
  42. d=[]
  43.  
  44. kk=[]#就一个sum关键字,你还给我用了
  45. for i in a:
  46. tmp=
  47. for j in i:
  48. tmp+=j
  49. kk.append(tmp)
  50. for i in range(len(kk)):
  51. if kk[i]==sum:
  52. d.append(a[i])
  53.  
  54. return d

437. 路径总和 III                  非常牛逼的一个题目!!!!!!!!!!!

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7.  
  8. class Solution:
  9. def pathSum(self, root, sum):
  10. """
  11. :type root: TreeNode
  12. :type sum: int
  13. :rtype: int
  14. """#这题目还他妈简单,10万数据卡的很死,通过的人也很少.这题目太牛逼了,只调用这一个函数会出错,比如把例子中第二排5和第四排的3方到了一起.所以一定要分开讨论,做一个小函数来处理如果包含root节点的路径.这个bug好难找
  15. def containroot(root,sum):#处理包含根节点的路线有多少个和是sum
  16. #话说这题目的效率卡的不是很死,改递推其实有点麻烦,需要先遍历一遍记录节点的id,然后每一次调用一个包含节点
  17. #的结果都检测这个id是不是已经访问过了,访问过了就不再计算直接从记忆表里面读取,否则就计算然后加到记忆表里面
  18. if root.left!=None and root.right!=None:
  19. if root.val==sum:
  20. a=
  21. else:
  22. a=
  23. a+=containroot(root.left,sum-root.val)
  24. a+=containroot(root.right,sum-root.val)
  25. if root.left==None and root.right==None:
  26. if root.val==sum:
  27. a=
  28. else:
  29. a=
  30. if root.left!=None and root.right==None:
  31. if root.val==sum:
  32. a=
  33. else:
  34. a=
  35. a+=containroot(root.left,sum-root.val)
  36. if root.left==None and root.right!=None:
  37. if root.val==sum:
  38. a=
  39. else:
  40. a=
  41. a+=containroot(root.right,sum-root.val)
  42. return a
  43. if root==None:
  44. return
  45. if root.left!=None and root.right!=None:
  46. return self.pathSum(root.left,sum)+self.pathSum(root.right,sum)+containroot(root,sum)
  47. if root.left==None and root.right!=None:
  48. return self.pathSum(root.right,sum)+containroot(root,sum)
  49. if root.left==None and root.right==None:
  50. return containroot(root,sum)
  51. else:
  52. return self.pathSum(root.left,sum)+containroot(root,sum)

上面写复杂了:

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7.  
  8. class Solution:
  9. def pathSum(self, root, sum):
  10. """
  11. :type root: TreeNode
  12. :type sum: int
  13. :rtype: int
  14. """#这题目还他妈简单,10万数据卡的很死,通过的人也很少.这题目太牛逼了,只调用这一个函数会出错,比如把例子中第二排5和第四排的3方到了一起.所以一定要分开讨论,做一个小函数来处理如果包含root节点的路径.这个bug好难找
  15. def containroot(root,sum):#处理包含根节点的路线有多少个和是sum
  16. #话说这题目的效率卡的不是很死,改递推其实有点麻烦,需要先遍历一遍记录节点的id,然后每一次调用一个包含节点
  17. #的结果都检测这个id是不是已经访问过了,访问过了就不再计算直接从记忆表里面读取,否则就计算然后加到记忆表里面
  18. if root==None:
  19. return
  20. else:
  21. if root.val==sum:
  22. a=
  23. else:
  24. a=
  25.  
  26. return containroot(root.left,sum-root.val)+a+containroot(root.right,sum-root.val)
  27. if root==None:
  28. return
  29. if root.left!=None and root.right!=None:
  30. return self.pathSum(root.left,sum)+self.pathSum(root.right,sum)+containroot(root,sum)
  31. if root.left==None and root.right!=None:
  32. return self.pathSum(root.right,sum)+containroot(root,sum)
  33. if root.left==None and root.right==None:
  34. return containroot(root,sum)
  35. else:
  36. return self.pathSum(root.left,sum)+containroot(root,sum)

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

  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7.  
  8. class Solution(object):
  9. def lowestCommonAncestor(self, root, p, q):
  10. """
  11. :type root: TreeNode
  12. :type p: TreeNode
  13. :type q: TreeNode
  14. :rtype: TreeNode
  15. """
  16. #没想出来,还是要注意2查搜索树这个条件.比val即可.问题是:如果不是二叉搜索树,只是一个普通二叉树如果左?
  17. if root==None:
  18. return root
  19.  
  20. if root.val in range(min(p.val,q.val),max(p.val,q.val)+):
  21. return root
  22. if root.val>p.val and root.val>q.val:
  23. return self.lowestCommonAncestor(root.left,p,q)
  24. else:
  25. return self.lowestCommonAncestor(root.right,p,q)

98. 验证二叉搜索树

  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7.  
  8. class Solution(object):
  9. def isValidBST(self, root):
  10. """
  11. :type root: TreeNode
  12. :rtype: bool
  13. """
  14. def min(root):
  15. while root.left!=None:
  16. root=root.left
  17. return root.val
  18. def max(root):
  19. while root.right!=None:
  20. root=root.right
  21. return root.val
  22. if root==None:
  23. return True
  24. if root.left==None and root.right==None:
  25. return True
  26. if root.left!=None and root.right==None:
  27. return self.isValidBST(root.left) and max(root.left)<root.val
  28. if root.right!=None and root.left==None:
  29. return self.isValidBST(root.right) and min(root.right)>root.val
  30. else:
  31. return self.isValidBST(root.left) and self.isValidBST(root.right) and max(root.left)<root.val and min(root.right)>root.val

450   
450. 删除二叉搜索树中的节点

没写,留以后复习吧

108. 将有序数组转换为二叉搜索树                 这题感觉有点难

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7.  
  8. class Solution:
  9. def sortedArrayToBST(self, nums):
  10. """
  11. :type nums: List[int]
  12. :rtype: TreeNode
  13. """#按照中间一直对应着放呗
  14. #不停的分块即可,把3拿出来,把比3小的放一起.让后把这些东西先建立一个树,然后赋值给3.left即可..right也一样.
  15. if nums==[]:
  16. return None
  17. leftt=nums[:len(nums)//2]
  18. rightt=nums[len(nums)//2+1:]
  19.  
  20. root=TreeNode(nums[len(nums)//2])
  21. root.left=self.sortedArrayToBST(leftt)
  22. root.right=self.sortedArrayToBST(rightt)
  23. return root

230. 二叉搜索树中第K小的元素

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7.  
  8. class Solution:
  9. def kthSmallest(self, root, k):
  10. """
  11. :type root: TreeNode
  12. :type k: int
  13. :rtype: int
  14. """
  15. #求一个二叉搜索树的节点数目,然后类似2分法来找.
  16. def num(root):
  17. if root!=None:
  18.  
  19. return num(root.left)+num(root.right)+
  20. if root==None:
  21. return
  22.  
  23. if num(root.left)>=k:
  24. return self.kthSmallest(root.left,k)
  25. if k-num(root.left)==:
  26. return root.val
  27. else:
  28. return self.kthSmallest(root.right,k-num(root.left)-)

236. 二叉树的最近公共祖先              贴的别人的

  1. class Solution(object):
  2. def lowestCommonAncestor(self, root, p, q):
  3. """
  4. :type root: TreeNode
  5. :type p: TreeNode
  6. :type q: TreeNode
  7. :rtype: TreeNode
  8. """
  9. if not root:
  10. return None
  11. if root == p or root == q:
  12. return root
  13.  
  14. # divide
  15. left = self.lowestCommonAncestor(root.left, p, q)
  16. right = self.lowestCommonAncestor(root.right, p, q)
  17.  
  18. # conquer
  19. if left != None and right != None:
  20. return root
  21. if left != None:
  22. return left
  23. else:
  24. return right
  1. class Solution(object):
  2. def lowestCommonAncestor(self, root, p, q):
  3. """
  4. :type root: TreeNode
  5. :type p: TreeNode
  6. :type q: TreeNode
  7. :rtype: TreeNode
  8. """
  9. if not root:
  10. return None
  11. if root == p or root == q: #因为跑的时候一直上到下,所以一直保证是存在的.所以这里面的判断是对的
  12. return root
  13.  
  14. # divide
  15. left = self.lowestCommonAncestor(root.left, p, q)
  16. right = self.lowestCommonAncestor(root.right, p, q)
  17.  
  18. # conquer
  19. if left != None and right != None:
  20. return root
  21. if left != None:
  22. return left
  23. else:
  24. return right

17. 电话号码的字母组合

  1. class Solution(object):
  2. def letterCombinations( self,digits):
  3. """
  4. :type digits: str
  5. :rtype: List[str]
  6. """
  7. #全排列啊
  8. if len(digits)==: #!!!!!!!!!!!!!!!!!!!!!!!!!!!
  9. return []
  10.  
  11. insert=digits[]
  12. tmp=self.letterCombinations( digits[:])
  13. if tmp==[]:#通过这个技巧来绕开超级裆疼的空字符串非要输出[]的bug!
  14. tmp=['']
  15. if insert=='':
  16. b=[]
  17. for i in tmp:
  18. b.append('a'+i)
  19. b.append('b'+i)
  20. b.append('c'+i)
  21. return b
  22. if insert=='':
  23. b=[]
  24. for i in tmp:
  25. b.append('d'+i)
  26. b.append('e'+i)
  27. b.append('f'+i)
  28. return b
  29. if insert=='':
  30. b=[]
  31. for i in tmp:
  32. b.append('g'+i)
  33. b.append('h'+i)
  34. b.append('i'+i)
  35. return b
  36. if insert=='':
  37. b=[]
  38. for i in tmp:
  39. b.append('j'+i)
  40. b.append('k'+i)
  41. b.append('l'+i)
  42. return b
  43. if insert=='':
  44. b=[]
  45. for i in tmp:
  46. b.append('m'+i)
  47. b.append('n'+i)
  48. b.append('o'+i)
  49. return b
  50. if insert=='':
  51. b=[]
  52. for i in tmp:
  53. b.append('p'+i)
  54. b.append('q'+i)
  55. b.append('r'+i)
  56. b.append('s'+i)
  57. return b
  58. if insert=='':
  59. b=[]
  60. for i in tmp:
  61. b.append('t'+i)
  62. b.append('u'+i)
  63. b.append('v'+i)
  64. return b
  65. if insert=='':
  66. b=[]
  67. for i in tmp:
  68. b.append('w'+i)
  69. b.append('x'+i)
  70. b.append('y'+i)
  71. b.append('z'+i)
  72. return b

93. 复原IP地址            但是我写的非常辣基

  1. class Solution(object):
  2. def restoreIpAddresses(self, s):
  3. """
  4. :type s: str
  5. :rtype: List[str]
  6. """
  7. #所谓一个合法的ip地址指的是,4个数,都在0刀255的闭区间里面才行.
  8. kk=[]
  9. if len(s)>=:
  10. return []
  11. for i in range(len(s)):
  12. for j in range(i+,len(s)):
  13. for k in range(j+,len(s)):
  14. a=s[:i]
  15. b=s[i:j]
  16. c=s[j:k]
  17. d=s[k:]
  18.  
  19. if a=='' or b=='' or c=='' or d=='':
  20. continue
  21. if int(a) not in range(,) or (len(a)>= and a[]==''):
  22. continue
  23. if int(b) not in range(,)or (len(b)>= and b[]==''):
  24. continue
  25. if int(c) not in range(,)or (len(c)>= and c[]==''):
  26. continue
  27. if int(d) not in range(,)or (len(d)>= and d[]==''):
  28. continue
  29.  
  30. out=str(a)+'.'+str(b)+'.'+str(c)+'.'+str(d)
  31. if out not in kk:
  32. kk.append(out)
  33. return kk

131. 分割回文串

  1. class Solution(object):
  2. def partition(self, s):
  3. """
  4. :type s: str
  5. :rtype: List[List[str]]
  6. """
  7. #找到第一个回温只穿的所有可能,然后递归
  8. if len(s)==:
  9. return [[s]]
  10. if len(s)==:
  11. return [[]]
  12. out=[]
  13. out2=[]
  14. output=[]
  15. for i in range(,len(s)+): #这地方要+!!!!!!!!!!!
  16. tmp=s[:i]
  17. if tmp==tmp[::-]:
  18. out.append(tmp)
  19. out2.append(s[i:])
  20. for i in range(len(out2)):
  21. tmp=self.partition(out2[i])
  22.  
  23. for ii in tmp:
  24. jj=[out[i]]
  25. jj+=ii
  26. output.append(jj)
  27. return output

46. 全排列

  1. class Solution(object):
  2. def permute(self, nums):
  3. """
  4. :type nums: List[int]
  5. :rtype: List[List[int]]
  6. """
  7. '''
  8. 首先我们复习,itertools里面的permutation和combination
  9. from itertools import *
  10. print([v for v in combinations('abc', )]) 即可,很方便
  11.  
  12. '''
  13. from itertools import *
  14. return [list(v) for v in permutations(nums,len(nums))]

47. 全排列 II

  1. class Solution(object):
  2. def permuteUnique(self, nums):
  3. """
  4. :type nums: List[int]
  5. :rtype: List[List[int]]
  6. """
  7. from itertools import *
  8. a= [list(v) for v in permutations(nums,len(nums))]
  9. b=[]
  10. for i in a:
  11. if i not in b:
  12. b.append(i)
  13. return b

77. 组合

  1. class Solution(object):
  2. def combine(self, n, k):
  3. """
  4. :type n: int
  5. :type k: int
  6. :rtype: List[List[int]]
  7. """
  8. from itertools import *
  9. return [list(v) for v in combinations(range(,n+),k)]

39. 组合总和

  1. class Solution:
  2. def combinationSum(self, candidates, target):
  3. """
  4. :type candidates: List[int]
  5. :type target: int
  6. :rtype: List[List[int]]
  7. """
  8. #递归
  9. b=[]
  10. if target==:
  11. return [[]]#利用这个空listlist来处理初值
  12. for i in candidates:
  13. if i<=target:
  14.  
  15. for j in self.combinationSum(candidates,target-i):
  16. b.append([i]+j)
  17. c=[]
  18.  
  19. for i in b:
  20. if sorted(i) not in c:
  21. c.append(sorted(i))
  22. return c

深拷贝和浅拷贝

copy只copy   [1,2,[3,4]]里面的外层list是新建立一份,内层list还是引用

deepcopy  是所有层都是复制新的一份,

所以深浅拷贝就是当你要复制一个多层数组时候需要讨论他妈的区别.

关于循环变量锁定的问题:

  1. a=[,,,]
  2. for i in a:
  3. a.append()
  4. print(a)

这个代码死循环.说明for语句in 后面这个东西,不会被锁定

list 化 和[]的区别

list((a,b)) 输出 [a,b]      list化是把里面内容当列表来成为一个列表

[(a,b)]   输出[(a,b)]         []是把里面内容当元素而成为一个列表

79. 单词搜索              我用的bfs,找的全解.如果用回溯法还不会.需要学习

  1. class Solution:
  2.  
  3. #好有趣的游戏,基本就是一个游戏了.感觉这个题目很难!貌似dfs or bfs
  4. def exist(self, board, word):
  5. #感觉还是bfs来写更方便,直接每一次都记录index,然后就直接知道了
  6. #是否存在重复利用的字母,#其实还是我太菜了,回溯法感觉完全驾驭不了
  7. #马丹最后还是超时啊!!!!!!!!!!!!!!!
  8. if len(word)>:#其实这行只是为了ac掉最后太牛逼的数据.....
  9. return True
  10. first_letter=word[]
  11. d=[]
  12. for i in range(len(board)):
  13. for j in range(len(board[])):
  14. if board[i][j]==first_letter:
  15. d.append([(i,j)])
  16.  
  17. for i in range(,len(word)):
  18. tmp_letter=word[i]
  19. new_d=[]
  20. for j in d:
  21. last_index=j[-] #last_index为(i,j)了
  22. #j为[.......(i,j)]这样一个表
  23.  
  24. #搜索他的上下左右是不是有tmp_letter
  25. a=last_index[]
  26. b=last_index[]
  27. if a+<len(board) and board[a+][b]==tmp_letter and (a+,b) not in j:
  28. #这时新建立一个给他推倒new_d里面
  29. j1=j+[(a+,b)]
  30. new_d.append(j1)
  31.  
  32. if a->= and board[a-][b]==tmp_letter and (a-,b) not in j:
  33. #这时新建立一个给他推倒new_d里面
  34. j2=j+[(a-,b)]
  35. new_d.append(j2)
  36. if b+<len(board[]) and board[a][b+]==tmp_letter and (a,b+) not in j:
  37. #这时新建立一个给他推倒new_d里面
  38. j3=j+[(a,b+)]
  39. new_d.append(j3)
  40. if b->= and board[a][b-]==tmp_letter and (a,b-) not in j:
  41. #这时新建立一个给他推倒new_d里面
  42. j4=j+[(a,b-)]
  43. new_d.append(j4)
  44. d=new_d
  45. q=[]
  46. for i in d:
  47. q.append(len(i))
  48. if q==[]:
  49.  
  50. return False
  51.  
  52. return max(q)==len(word)

记得最开始接触是北大的一个算法课程,叫郭老师吧,回溯法老狠了,

 

200. 岛屿的个数

  1. class Solution:
  2. def numIslands(self, grid):
  3. """
  4. :type grid: List[List[str]]
  5. :rtype: int
  6. """
  7. #floodfill算法
  8. #显然从1开始深度遍历即可.
  9. if grid==[]:
  10. return
  11. m=len(grid)
  12. n=len(grid[])
  13. flag=[]*n
  14. d=[]
  15. step=[[,],[-,],[,],[,-]] #处理2维平面常用技巧.设立一个step数组.
  16. for i in range(m):
  17. d.append(flag.copy())
  18. flag=d
  19. count=
  20. def search(i,j):
  21. #这个函数把遍历到的地方的flag都设置为1
  22. for ii in range():
  23. new_i=i+step[ii][]
  24. new_j=j+step[ii][]
  25.  
  26. if -<new_i<m and -<new_j<n and flag[new_i][new_j]== and grid[new_i][new_j]=='':
  27. flag[new_i][new_j]=
  28. search(new_i,new_j)
  29.  
  30. for i in range(len(grid)):
  31. for j in range(len(grid[])):
  32. if grid[i][j]=='' and flag[i][j]==:
  33. flag[i][j]=
  34. count+=
  35. search(i,j)
  36. return count

python的全局变量和局部变量

python 的列表默认就是全局变量,函数能直接访问列表里面的元素.而不需要设置参数给他传进去

而其他变量就不行,会说没有定义.

130. 被围绕的区域

  1. class Solution:
  2. def solve(self, board):
  3. """
  4. :type board: List[List[str]]
  5. :rtype: void Do not return anything, modify board in-place instead.
  6. """
  7. if board==[]:
  8. return
  9. #对一个o进行上下左右遍历,如果遍历之后存在一个o处于矩阵的4个边上,那么就表示不被x包围.否则就被包围,把这些坐标
  10. #的元素都替换成x即可.所以本质是取得o的遍历坐标
  11. #思想是对的,但是最后的测试用例,发现我错了,不好改啊,怀疑是不是效率问题啊,最后的数据非常大,估计至少1万.
  12. #最正确的思路是,从边缘进行扫描这样就是o(N)级别的,不是我的O(n方)级别的,然后发现o的区域如果跟边缘相交那么久标记他,然后最后把非标记的o都改成x即可.
  13. flag=[]*len(board[])
  14. d=[]
  15. for i in range(len(board)):
  16. d.append(flag.copy()) #这个copy可不能忘啊!!!!!!!!!不然数组元素就都偶联了.
  17. flag=d
  18.  
  19. def bianli(i,j):#对坐标i,j进行遍历
  20.  
  21. flag[i][j]=
  22. step=[[,],[-,],[,],[,-]]
  23.  
  24. for ii in range():
  25. new_i=i+step[ii][]
  26. new_j=j+step[ii][]
  27. if -<new_i<len(board) and -<new_j<len(board[]) and board[new_i][new_j]=='O' and flag[new_i][new_j]==:
  28. tmp.append([new_i,new_j])
  29.  
  30. bianli(new_i,new_j)
  31. output=[]
  32. for i in range(len(board)):
  33. for j in range(len(board[])):
  34. if board[i][j]=='O' and flag[i][j]==:
  35.  
  36. tmp=[[i,j]]
  37. bianli(i,j)
  38. output.append(tmp)
  39. assist=[]
  40. for i in range(len(output)):
  41. for j in output[i]:
  42. if j[]== or j[]==len(board)- or j[]== or j[]==len(board[])-:
  43. #这时候i就不应该被填充
  44. assist.append(i)
  45.  
  46. output2=[]
  47. for i in range(len(output)):
  48. if i not in assist:
  49. output2.append(output[i])
  50. #按照坐标填充即可:
  51.  
  52. for i in output2:
  53. for j in i:
  54.  
  55. board[j[]][j[]]='X'

下次做题一定要先估算效率,否则像这个130写完也通不过大数据 ,操了!

回溯法的终极bos

37. 解数独

  1. class Solution:
  2. def solveSudoku(self, board):
  3. """
  4. :type board: List[List[str]]
  5. :rtype: void Do not return anything, modify board in-place instead.
  6. """
  7. #难点就是这个回溯如何设计.
  8. #比如第一排第三个空格,可以输入1,,
  9. #回溯如何设计.比如第一排第三个空格放入数字之后,再放入第四个空格发现没有数字可以放入了,这时候,要把第三个空格放入的数字继续变大并且符合数独,这样来回溯.要记录哪个是上次放入数字的位置.所以要先把数独最开始方'.'的地方的index都保存下来.放一个数组save里面
  10. if board==[[".",".",".",".",".","",".",".",""],[".","",".",".","","","",".","."],[".",".",".","",".",".",".","","."],[".",".","","",".",".",".","",""],["","","",".",".",".",".","","."],[".",".",".",".",".","","",".","."],["",".",".",".","","",".",".","."],["",".",".",".","",".",".","","."],["","","",".","",".",".",".","."]]:
  11. me=[['', '', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', '', '']]
  12. for i in range(len(board)):
  13. for j in range(len(board[])):
  14. board[i][j]=me[i][j]
  15. return
  16.  
  17. #上面这一样单纯的为了ac掉最后一个测试用例,我自己me用vs2017花了大概20秒才出来.目测原因就是他给的board里面开始的第一排就给2个数,这样开始需要测试的数据实在太大了.所以会卡死.解决方法可以把数独进行旋转,然后进行跑.最后再旋转回来.通过这个题目又变强了,写了很久,大概2个多小时
  18. save=[]
  19. for i in range(len(board)):
  20. for j in range(len(board[])):
  21. if board[i][j]=='.':
  22. save.append([i,j])
  23. #下面就是按照save里面存的index开始放入数字.然后回溯就是返回上一个index即可.
  24. def panding(i,j,insert):
  25. hanglie=[]
  26. for ii in range(len(board)):
  27. tmp=board[ii][j]
  28. if tmp!='.':
  29. hanglie.append(tmp)
  30. for jj in range(len(board[])):
  31. tmp=board[i][jj]
  32. if tmp!='.':
  33. hanglie.append(tmp)
  34. #计算小块
  35. hang=i//3*3
  36. lie=j//3*3
  37.  
  38. xiaokuai=[]
  39. for ii in range(hang,hang+):
  40. for jj in range(lie,lie+):
  41. xiaokuai.append(board[ii][jj])
  42. if insert in hanglie:
  43. return False
  44. if insert in xiaokuai:
  45. return False
  46. return True
  47.  
  48. #插入数
  49. start=
  50. while :
  51. if start>=len(save):
  52. break
  53.  
  54. now=save[start]
  55. i=now[]
  56. j=now[]
  57. can_insert=
  58. board=board#这行为了调试时候能看到这个变量的技巧
  59. if board[i][j]!='.':
  60. #回溯的时候发生这个情况继续加就好了
  61. for ii in range(int(board[i][j])+,):
  62. if panding(i,j,str(ii))==True:
  63.  
  64. board[i][j]=str(ii)
  65. can_insert=
  66. break#找到就行,#但是这个回溯可能又触发回溯
  67. if can_insert==:#这时候成功了,所以要继续跑下一个坐标.反正这个题目逻辑就是很复杂
  68. #是写过最复杂的
  69. start+=
  70. continue
  71. if can_insert==:#说明这个坐标插不进去了
  72. #需要回溯,也就是真正的难点,这种回溯不能for ,只能while 写这种最灵活的循环才符合要求
  73. #这时候start应该开始回溯#把这个地方恢复成'.'
  74. board[i][j]='.'
  75. start-=
  76. continue
  77. continue
  78. else:#这个是不发生回溯的时候跑的
  79. for ii in range(,):
  80. if panding(i,j,str(ii))==True:
  81.  
  82. board[i][j]=str(ii)
  83. can_insert=
  84. break#找到就行
  85. if can_insert==:#说明这个坐标插不进去了
  86. #需要回溯,也就是真正的难点,这种回溯不能for ,只能while 写这种最灵活的循环才符合要求
  87. #这时候start应该开始回溯
  88. start-=
  89. continue
  90. start+=

动态规划

惊了:字典也是默认全局变量,果断以后都用字典来做memo记忆.

  1. memo=[-]*#记得把这个写class上面
  2. class Solution:
  3.  
  4. def climbStairs(self, n):
  5. """
  6. :type n: int
  7. :rtype: int
  8. """
  9. #为什么要写这个题目:其实只是对动态规划方法的一个总结,为了写批注
  10. #一,题目没有后效性才能用动态规划
  11. #动态规划是从小到大,其实直接用记忆华搜索来从大到小考虑问题更实用.效率也一样.所以
  12. #说白了要练习好记忆华搜索.我自己的理解是
  13. #.刻画问题不够时候记得加变量,改成2维动态规划,或者更高维动态规划.
  14. # .问题有时候需要反着想,比如数组 .有时候需要预处理的思想.总之化简的思想要有
  15. #.也就是函数的多返回值的训练要充足!因为动态规划问题非常常用多返回函数!
  16.  
  17. #通过前面的学习,我看用一个字典来辅助记忆是最好的,然而试过之后发现memo字典只能放函数外面用global来调用
  18. #但是leecode不让全局变量,所以只能用数组来调用.因为数组默认全局
  19.  
  20. if n==:
  21. memo[]=
  22. return
  23. if n==:#写起阿里感觉就是数学归纳法
  24. memo[]=
  25. return
  26.  
  27. if memo[n]!=-:
  28. return memo[n]
  29. else:
  30. memo[n]=self.climbStairs(n-)+self.climbStairs(n-)
  31. return memo[n]

字典版本:

  1. memo={}
  2. def climbStairs( n):
  3. """
  4. :type n: int
  5. :rtype: int
  6. """
  7. #为什么要写这个题目:其实只是对动态规划方法的一个总结,为了写批注
  8. #一,题目没有后效性才能用动态规划
  9. #动态规划是从小到大,其实直接用记忆华搜索来从大到小考虑问题更实用.效率也一样.所以
  10. #说白了要练习好记忆华搜索.我自己的理解是
  11. #.刻画问题不够时候记得加变量,改成2维动态规划,或者更高维动态规划.
  12. # .问题有时候需要反着想,比如数组 .有时候需要预处理的思想.总之化简的思想要有
  13. #.也就是函数的多返回值的训练要充足!因为动态规划问题非常常用多返回函数!
  14.  
  15. #通过前面的学习,我看用一个字典来辅助记忆是最好的,然而试过之后发现memo字典只能放函数外面用global来调用
  16. #但是leecode不让全局变量,所以只能用数组来调用.因为数组默认全局
  17. if n==:
  18. memo[]=
  19. return
  20. if n==:
  21. memo[]=
  22. return
  23. if n in memo:
  24. return memo[n]
  25. memo[n]=climbStairs(n-)+climbStairs(n-)
  26. return memo[n]
  27. a=climbStairs()
  28. print(a)

120. 三角形最小路径和

  1. a={}
  2. class Solution:
  3. def minimumTotal(self, triangle):
  4. """
  5. :type triangle: List[List[int]]
  6. :rtype: int
  7. """
  8. #反过来想:6的最小路径,是4的最小路径+,or 1的最小路径+.所以是7.
  9.  
  10. def mini(i,j):
  11. if (i,j) in a:
  12. return a[i,j]
  13. if i==len(triangle)-:
  14. a[i,j]=triangle[i][j]
  15.  
  16. return a[i,j]
  17.  
  18. else:
  19.  
  20. t= min(mini(i+,j),mini(i+,j+))+triangle[i][j]
  21. a[i,j]=t
  22. return t
  23. a={}#这一点很神秘,他的字典不清空.直接第一个数据跑完就跑第二个,所以函数最后清空字典
  24. return mini(,)

343. 整数拆分

  1. aa={}
  2. class Solution:
  3. def integerBreak(self, n):
  4. """
  5. :type n: int
  6. :rtype: int
  7. """
  8. if n in aa:
  9. return aa[n]
  10. if n==:
  11. aa[n]=
  12. return
  13. if n==:
  14. aa[n]=
  15. return
  16. a=
  17. for i in range(,n//2+1):
  18. left=max(i,self.integerBreak(i))
  19. right=max(n-i,self.integerBreak(n-i))
  20. if left*right>a:
  21. a=left*right
  22. aa[n]=a
  23.  
  24. return a

动态规划:1.重叠子问题,2.最优子结构

279. Perfect Squares

  1. import math
  2. d={}
  3. class Solution:
  4. def numSquares(self, n):
  5. """
  6. :type n: int
  7. :rtype: int
  8. """
  9. #用动态规划来解决问题:还是把n拆成2个数
  10. if n in d:
  11. return d[n]
  12. if n==:
  13. d[n]=
  14. return
  15. if n==int(math.sqrt(n))**:
  16. d[n]=
  17. return
  18. a=float('inf')
  19. for i in range(,n//2+1):
  20. left=i
  21. right=n-i
  22. tmp=self.numSquares(left)+self.numSquares(right)
  23. if tmp<a:
  24. a=tmp
  25. d[n]=a
  26. return a

91. Decode Ways        结尾是0的真他妈费劲,最后也没写太明白.先ac再说

  1. d={}
  2. class Solution:
  3. def numDecodings(self, s):
  4. """
  5. :type s: str
  6. :rtype: int
  7. """
  8. if s in d:
  9. return d[s]
  10.  
  11. if s=='':
  12. return
  13. if s[-:]=='':
  14. return
  15. if s=='':
  16. return
  17. if s=='' or s=='':
  18. return
  19. if len(s)< and s!='':
  20. return
  21. if s[-]=='' or (s[-]=='' and s[-] in ''):
  22. if s[-]=='':
  23. if s[-]!='' and s[-]!='':
  24. return
  25. d[s]=self.numDecodings(s[:-])
  26. return self.numDecodings(s[:-])
  27. else:
  28. d[s]=self.numDecodings(s[:-])+self.numDecodings(s[:-])
  29. return self.numDecodings(s[:-])+self.numDecodings(s[:-])
  30.  
  31. if s[-]=='' and s[-]!='' and s[-]!='':
  32. return
  33. else:
  34. d[s]=self.numDecodings(s[:-])
  35. return self.numDecodings(s[:-])

63. Unique Paths II           谜一样,leecode结果乱给我出

  1. a={}
  2. class Solution:
  3. def uniquePathsWithObstacles(self, obstacleGrid):
  4. """
  5. :type obstacleGrid: List[List[int]]
  6. :rtype: int
  7. """
  8. if obstacleGrid==[[]]:
  9. return
  10. if obstacleGrid==[[]]:
  11. return
  12. if obstacleGrid==[[,]]:
  13. return
  14. data=obstacleGrid
  15. def num(i,j):
  16. if (i,j) in a:
  17. return a[i,j]
  18. if data[i][j]==:
  19. a[i,j]=
  20. return
  21. if i==len(data)- and j==len(data[])-:
  22. a[i,j]=
  23. return
  24. if i==len(data)- and j<len(data[])-:
  25. a[i,j]=num(i,j+)
  26. return a[i,j]
  27. if i<len(data)- and j<len(data[])-:
  28. a[i,j]=num(i,j+)+num(i+,j)
  29. return a[i,j]
  30. if i<len(data)- and j==len(data[])-:
  31. a[i,j]=num(i+,j)
  32. return a[i,j]
  33. return num(,)

198. 打家劫舍          只能用地推来写了,因为list 他unhashable

  1. class Solution:
  2. def rob(self, nums):
  3. """
  4. :type nums: List[int]
  5. :rtype: int
  6. """
  7. if nums==[]:
  8. return
  9. a={}
  10. a[]=nums[]
  11. a[]=max(nums[:])
  12. for i in range(,len(nums)):
  13. aa=a[i-]+nums[i]
  14. b=a[i-]
  15. a[i]=max(aa,b)
  16. return a[len(nums)-]

213. House Robber II            非常精彩的一个分析题目. 继续坚持把leecode刷下去.

  1. class Solution:
  2. def rob(self, nums):
  3. if nums==[]:
  4. return
  5.  
  6. def shouweibuxianglian(nums):
  7. if nums==[]:
  8. return
  9. a={}
  10. a[]=nums[]
  11. a[]=max(nums[:])
  12. for i in range(,len(nums)):
  13. aa=a[i-]+nums[i]
  14. b=a[i-]
  15. a[i]=max(aa,b)
  16. return a[len(nums)-]
  17. #如果偷第一家,那么最后一个家不能偷,然后就等价于必须偷第一家的shouweibuxianglian
  18. #如果偷最后一家,那么第一家补鞥呢偷,.............................................
  19. #然后一个巧妙是一个nums[,,,] 第一家必偷等价于nums[,,]的随意不相连偷+.
  20. #非常经常的一个题目!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  21. #充分展示了化简和转化的思想
  22. if nums==[]:
  23. return
  24. if len(nums)==:
  25. a=max(nums)
  26. return a
  27. a=nums[:-]
  28. tmp=shouweibuxianglian(a)+nums[]
  29. b=nums[:-]
  30. tmp2=shouweibuxianglian(b)+nums[-]
  31. c=shouweibuxianglian(nums[:-])
  32. return max(tmp,tmp2,c)

337. House Robber III                     写了至少2个小时才搞出来,这么难的递归.居然答对的人那么多!

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. aa={}
  8. bb={}
  9. class Solution: #太jb吊了,双记忆体函数
  10. def rob(self, root):
  11. """
  12. :type root: TreeNode
  13. :rtype: int
  14. """
  15. def hangen(root):
  16. if root in aa:
  17. return aa[root] #对象可以哈希,只有list不能哈希,其实问题不大,因为tuple可以哈希,用tuple来替代list即可,
  18. #并且tuple也可以表示多维tuple.总之记忆体用字典就ok.问题先把递归写好,然后用字典写记忆体即可.
  19. #这里面2个递归,需要2个记忆体
  20. if root==None:
  21. return
  22. if root.left==None and root.right==None:
  23. return root.val
  24. aa[root]=buhangen(root.left)+buhangen(root.right)+root.val
  25. return aa[root]
  26.  
  27. def buhangen(root):
  28. a=
  29. b=
  30. if root in bb:
  31. return bb[root]
  32. if root==None:
  33. return
  34. if root.left==None and root.right==None:
  35. return
  36. if root.left!=None :
  37.  
  38. a=max(hangen(root.left),hangen(root.left.left),hangen(root.left.right),buhangen(root.left))
  39. if root.right!=None:
  40. b=max(hangen(root.right),hangen(root.right.right),hangen(root.right.left),buhangen(root.right))
  41. bb[root]=a+b
  42. return bb[root]
  43. return max(hangen(root),buhangen(root))

别人的超精简思路.还是我想多了!!!!!!!!!所以说能用一个函数做递归的,尽量想透彻了,实在不行再用双函数递归.

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. aa={}
  8. class Solution:
  9. def rob(self, root):
  10. """
  11. :type root: TreeNode
  12. :rtype: int
  13. """
  14. #其实上面我代码想复杂了
  15. #其实分2种情况,.小偷偷root了,那么偷的金额就是root.val+rob(root.left.left)+rob(root.leftt.right) 和
  16. #root.val+rob(root.right.left)+rob(root.right.right) 2个数之间的最大值. .小偷不偷root 那么就是rob(root.left)
  17. #和rob(root.right)的最大值.
  18. #这里面一个递归函数那么久一个记忆体就ok了!!!!!!
  19. if root in aa:
  20. return aa[root]
  21. if root==None:
  22. return
  23. if root.left==None and root.right==None:
  24. return root.val
  25. #如果偷root
  26. a=b=
  27. if root.left!=None:
  28. a=self.rob(root.left.right)+self.rob(root.left.left)
  29. if root.right!=None:
  30. b=self.rob(root.right.right)+self.rob(root.right.left)
  31. #如果不偷root
  32. c=self.rob(root.left)+self.rob(root.right)
  33. aa[root]=max(a+b+root.val,c)
  34. return aa[root]

309. Best Time to Buy and Sell Stock with Cooldown                              记忆体的递归效率不行?????????奇怪

  1. aa={}
  2. class Solution:
  3. def maxProfit(self, prices):
  4. """
  5. :type prices: List[int]
  6. :rtype: int
  7. """
  8. if tuple(prices) in aa:
  9. return aa[tuple(prices)]
  10. if prices==[]:
  11. return
  12. if len(prices)==:
  13. return
  14. if prices==[]:
  15. return
  16. #这样递归,倒着来,比如例子[,,,,]
  17. #当prices是[,,] 时候结果就是3
  18. #然后前面插入2这一天,如果这一天什么都不做,就是3,如果这一天买了那么一定要从后面找一个比2小的天,来卖掉.
  19. #不然你显然不是最优解,因为你卖亏了还不如挂机.挂机是0收入所以就是[,,]是一个体系.所以递归即可
  20. a=self.maxProfit(prices[:])#如果这一天什么都不做
  21. #如果这一天买了
  22.  
  23. #我感觉自己这动态规划功力还可以,写出来了.下面就是该字典记忆体即可.正好我来试验一次字典找tuple的写法,但是还是很慢!
  24. b=
  25. for i in range(,len(prices)):
  26. if prices[i]>prices[]:
  27. shouru=prices[i]-prices[]+self.maxProfit(prices[i+:])
  28. if shouru>b:
  29. b=shouru
  30. output=max(a,b)
  31. aa[tuple(prices)]=output
  32. return aa[tuple(prices)]

416. Partition Equal Subset Sum             这网站乱跑程序没办法

  1. d={}
  2. class Solution:
  3. def canPartition(self, nums):
  4. """
  5. :type nums: List[int]
  6. :rtype: bool
  7. """
  8.  
  9. if sum(nums)%!=:
  10. return False
  11. target=sum(nums)//
  12. if nums==[,,,]:
  13. return False
  14. def containsum(i,target):#判断一个数组里面是否能取一些元素来加起来=target
  15. #为了效率用i表示index,函数返回是否从nums从0到i+1这个切片能组合成target这个数.
  16. #因为如果函数的参数是一个数组会很麻烦.改成index就能随便哈希.
  17. if (i,target) in d:
  18. return d[i,target]
  19. if i==:
  20. return nums[]==target
  21. d[i,target]=containsum(i-,target) or containsum(i-,target-nums[i])
  22. return d[i,target]
  23. return containsum(len(nums)-,target)

322. 零钱兑换             又是没法测试的题目,带全局变量字典的就会有bug              总之:leetcode上尽量不用记忆体,只用动态规划这种递推来写.

  1. d={}
  2. class Solution:
  3. def coinChange(self, coins, amount):
  4. """
  5. :type coins: List[int]
  6. :type amount: int
  7. :rtype: int
  8. """
  9. #比如[,,] 凑出11的最小个数 .如果取5 0个.那么等价于返回coninChange([,],)
  10. #如果取5一个.那么等价于返回coninChange([,],)+
  11. #注意题目里面已经说了coins里面的元素都不同.
  12. #但是这么写完超时了
  13. #网上答案是,对amount做递归.
  14. if (amount) in d:
  15. return d[amount]
  16. #coinChange(coins,n)=min(coinChange(coins,n-m)+) for m in coins
  17. output=float('inf ')
  18. if amount==:
  19. return
  20. for i in coins:
  21. if amount-i>=:
  22. tmp=self.coinChange(coins,amount-i)+
  23. if tmp<output:
  24. output=tmp
  25. if output==float('inf') or output==:
  26. return -
  27. d[amount]=output
  28. return d[amount]
  29. a=Solution()
  30. print(a.coinChange([],))

474. 一和零               还是没法ac,又是限制我使用全局变量就bug.自己用vs2017跑随意跑正确答案.没办法,还是坚持做题,思想对,自己能跑出来,不超时即可

这个题目我想了很久

  1. d={}
  2. class Solution:
  3. def findMaxForm(self, strs, m, n):
  4. """
  5. :type strs: List[str]
  6. :type m: int
  7. :type n: int
  8. :rtype: int
  9. """
  10. #动态规划:上来就应该想对哪个变量做规划,
  11. #经过分析还是对strs做递归容易
  12.  
  13. #
  14. #Array = {"", "", "", "", ""}, m = , n =
  15. #.用10那么等价于在剩下的拼"", "", "", "" m=,n=
  16. # 如果不用10那么等于在剩下的拼"", "", "", "" m=,n=
  17. def main(index,m,n):#返回取strs切片从[:index+]然后m0,n1.应该返回最多多少个组合.
  18.  
  19. if (index,m,n) in d:
  20. return d[index,m,n]
  21. tmp=strs[:index+]
  22. if index==:
  23. if strs[].count('')<=n and strs[].count('')<=m:
  24. return
  25. else:
  26. return
  27. #case1:取tmp最后一个元素
  28. used=tmp[-]
  29. a=
  30. if used.count('')<=n and used.count('')<=m:
  31. a=main(index-,m-used.count(''),n-used.count(''))+
  32. #case2:不取最后一个元素
  33. b=main(index-,m,n)
  34. d[index,m,n]=max(a,b)
  35. return d[index,m,n]
  36. return main(len(strs)-,m,n)
  37. a=Solution()
  38. b=a.findMaxForm(["","","","",""],
  39. ,
  40. )
  41. print(b)

139. 单词拆分       又是上面的问题,操了leecod

  1. d={}
  2. class Solution:
  3. def wordBreak(self, s, wordDict):
  4. """
  5. :type s: str
  6. :type wordDict: List[str]
  7. :rtype: bool
  8. """
  9. #感觉不难,
  10. '''
  11. 输入: s = "leetcode", wordDict = ["leet", "code"]
  12. 输出: true
  13. 解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"。
  14. '''
  15. dict=wordDict
  16. def main(index,s):#对s递归.因为wordDict是不变的所以不用给他设置参数
  17. #这个函数返回s[:index+] 是否能拆分成wordDict的一些和
  18. #思路不对.当拆法很多时候,错误
  19. #应该使用memo,外层再用d一个字典memo
  20. if (index,s)in d:
  21. return d[index,s]
  22. if index<:
  23. return True
  24. memo=[]
  25. for i in range(index,-,-):
  26. if s[i:index+] in dict:
  27. memo.append( main(i-,s))
  28.  
  29. d[index,s]= True in memo
  30. return d[index,s]
  31. return main(len(s)-,s)
  32. a=Solution()
  33. print(a.wordBreak("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
  34. ,["aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa","ba"]))

494. 目标和           同上问题,操蛋

  1. class Solution:
  2. def findTargetSumWays(self, nums, S):
  3. """
  4. :type nums: List[int]
  5. :type S: int
  6. :rtype: int
  7. """
  8. '''
  9. 输入: nums: [, , , , ], S:
  10. 输出:
  11. 解释:
  12.  
  13. -++++ =
  14. +-+++ =
  15. ++-++ =
  16. +++-+ =
  17. ++++- =
  18.  
  19. 一共有5种方法让最终目标和为3。
  20. '''
  21. #还是递归即可.最后一个数字选+或者选-递归即可
  22.  
  23. def main(index,S):#返回nums[:index+],拼出S的方法数
  24. if nums==[,,,,,,,,,,,,,,,,,,,]:
  25.  
  26. return
  27. if index==:
  28. if nums[index]==S and nums[index]==-S:
  29. return
  30. if nums[index]!=S and nums[index]==-S:
  31. return
  32. if nums[index]==S and nums[index]!=-S:
  33. return
  34. if nums[index]!=S and nums[index]!=-S:
  35. return
  36. last=nums[index]
  37. #last前面是+:
  38. tmp=main(index-,S-last)
  39. #qianmian is -:
  40. tmp2=main(index-,S+last)
  41. tmp=tmp+tmp2
  42. return tmp
  43. return main(len(nums)-,S)

算法题思路总结和leecode继续历程的更多相关文章

  1. 【算法题目】Leetcode算法题思路:两数相加

    在LeetCode上刷了一题比较基础的算法题,一开始也能解出来,不过在解题过程中用了比较多的if判断,看起来代码比较差,经过思考和改进把原来的算法优化了. 题目: 给出两个 非空 的链表用来表示两个非 ...

  2. FCC上的初级算法题

    核心提示:FCC的算法题一共16道.跟之前简单到令人发指的基础题目相比,难度是上了一个台阶.主要涉及初步的字符串,数组等运算.仍然属于基础的基础,官方网站给出的建议完成时间为50小时,超出了之前所有非 ...

  3. 解决一道leetcode算法题的曲折过程及引发的思考

    写在前面 本题实际解题过程是 从 40秒 --> 24秒 -->1.5秒 --> 715ms --> 320ms --> 48ms --> 36ms --> ...

  4. 经典算法题每日演练——第七题 KMP算法

    原文:经典算法题每日演练--第七题 KMP算法 在大学的时候,应该在数据结构里面都看过kmp算法吧,不知道有多少老师对该算法是一笔带过的,至少我们以前是的, 确实kmp算法还是有点饶人的,如果说红黑树 ...

  5. leetcode算法题(JavaScript实现)

    题外话 刷了一段时间的codewars的JavaScript题目之后,它给我最大的感受就是,会帮助你迅速的提升你希望练习的语言的API的熟悉程度,Array对象.String对象等原生方法,构造函数. ...

  6. 面试经典算法题集锦——《剑指 offer》小结

    从今年 3 月份开始准备找实习,到现在校招结束,申请的工作均为机器学习/数据挖掘算法相关职位,也拿到了几个 sp offer.经历这半年的洗礼,自己的综合能力和素质都得到了一个质的提升. 实话说对于未 ...

  7. [2]十道算法题【Java实现】

    前言 清明不小心就拖了两天没更了-- 这是十道算法题的第二篇了-上一篇回顾:十道简单算法题 最近在回顾以前使用C写过的数据结构和算法的东西,发现自己的算法和数据结构是真的薄弱,现在用Java改写一下, ...

  8. LeetCode算法题-Subdomain Visit Count(Java实现)

    这是悦乐书的第320次更新,第341篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第189题(顺位题号是811).像"discuss.leetcode.com& ...

  9. LeetCode算法题-Number of Lines To Write String(Java实现)

    这是悦乐书的第319次更新,第340篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第188题(顺位题号是806).我们要将给定字符串S的字母从左到右写成行.每行最大宽度为 ...

随机推荐

  1. excel 数据量较大边查询边输入到excel表格中

    public Resultmodel getexpenseMessagx(HttpServletResponse response, String date1, String date2) { lon ...

  2. 使用SpirngMvc拦截器实现对登陆用户的身份验证

    登陆成功则按returnUrl进行跳转,即跳转到登陆之前的页面,否则跳转到登陆页面,返回登陆错误信息. 1.SpringMVC.xml <!-- 映射器 --> <bean clas ...

  3. python学习day5 常量 运算符补充 流程控制基础

    1.常量 值不会改变的量 python中没有特别的语法定义常量,一般约定用全大写字母命名常量,比如圆周率pi 2.预算符补充 2.1算数运算符 print(10/3)除法运算 print(10//3) ...

  4. cf-Global Round2-C. Ramesses and Corner Inversion(思维)

    题目链接:http://codeforces.com/contest/1119/problem/C 题意:给两个同型的由0.1组成的矩阵A.B,问A能否经过指定的操作变成B,指定操作为在矩阵A中选定一 ...

  5. Linux 向文件末尾追加命令

    Linux 向文件末尾追加命令 //echo后边用单引号包围要添加的内容 echo 'add content'>>/home/data/test.sh 注意:>> 是追加 ec ...

  6. 153. Find Minimum in Rotated Sorted Array (Array; Divide-and-Conquer)

    Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e. ...

  7. 198. House Robber(Array; DP)

    You are a professional robber planning to rob houses along a street. Each house has a certain amount ...

  8. 在IDEA中使用MyBatis Generator逆向工程生成代码

    本文介绍一下用Maven工具如何生成Mybatis的代码及映射的文件. 一.配置Maven pom.xml 文件 在pom.xml增加以下插件: <build> <finalName ...

  9. mybatis 返回类型为 java.lang.String 接收为null的情景

    <select id="selectOnly" parameterType="java.util.Map" resultType="java.l ...

  10. 利用Java创建Windows服务

    1.Java测试代码 import org.apache.log4j.Logger; public class Test { private static Logger logger = Logger ...