├── .gitignore ├── 01_Math ├── Pics │ └── bayesian.png ├── README.ipynb └── README.md ├── 02_ML_knowledge ├── Pics │ ├── bayesian.png │ ├── cluster.png │ └── cluster2.jpg ├── README.ipynb └── README.md ├── 03_DL_knowledge ├── 01_线性回归.ipynb ├── 02_分类模型和Softmax.ipynb ├── 03_多层感知机.ipynb ├── 04_模型选择(过拟合欠拟合出现和解决).ipynb ├── 05_数值稳定性与模型初始化.ipynb ├── 06_卷积神经网络.ipynb ├── 08_注意力机制.ipynb ├── 09_优化.ipynb ├── 10_模型微调.ipynb ├── Pics │ ├── ALEX.png │ ├── Conjugate_gradient_illustration.png │ ├── MLE1.png │ ├── MLE2.png │ ├── NIN.png │ ├── Nesterov.png │ ├── Nesterovshow.png │ ├── Nesterovshow2.png │ ├── OVERFIT.png │ ├── SENET.png │ ├── SGDupdate.png │ ├── Uniform.png │ ├── VGG.png │ ├── activation.png │ ├── conv.png │ ├── convbias.png │ ├── convdia.png │ ├── convexfun.svg │ ├── convexfunset.svg │ ├── convexset.png │ ├── convmulc.png │ ├── convsize.gif │ ├── convstruct.png │ ├── corr.png │ ├── cross_ent.png │ ├── densenet.png │ ├── densenetjump.png │ ├── dropout.png │ ├── fc.png │ ├── gconv.png │ ├── googlenet.png │ ├── googlenet_full.png │ ├── lenet.png │ ├── linearloss.png │ ├── localmin.svg │ ├── loss_reg.png │ ├── minmul.png │ ├── minmulcal.png │ ├── minmulexp.png │ ├── multi.svg │ ├── poolgrad.png │ ├── res.svg │ ├── res1.svg │ ├── residual.png │ ├── ressquare.svg │ ├── saddle.svg │ ├── senetres.png │ ├── softmax.png │ ├── testtrainerror.svg │ ├── vanishgradient.svg │ ├── x2.svg │ ├── x2big.svg │ ├── x2nonconvex.svg │ └── x2small.svg ├── README.ipynb ├── README.md └── dcgan_faces_tutorial.ipynb ├── 04_Algorithms ├── Leetcode │ ├── 0-1 knapsack.py │ ├── 011.py │ ├── 0827.py │ ├── 2. Add Two Numbers.py │ ├── 2.2 Fast Power.py │ ├── 2.2 Greatest Common Divisor.py │ ├── 2.2 Is Prime.py │ ├── 2.3 Cnk.py │ ├── 2.3 Guassian Elimination.py │ ├── 3.1 Fenwick Tree.py │ ├── Ad-Hoc_move the bishop.py │ ├── B01.py │ ├── B02.py │ ├── BFS.py │ ├── Baidu02.py │ ├── Binary Search_Strange Distance.py │ ├── Cats and Dogs.py │ ├── Charlie New PC.py │ ├── Collecting Gold.py │ ├── Concentration Game.py │ ├── ConstructGraph.py │ ├── Debug_BST.py │ ├── Dynamic programming Gotta Catch 'Em All.py │ ├── Fast and curious.py │ ├── Fill The Pixels.py │ ├── Impact Factor.py │ ├── Infinite String.py │ ├── Interactive Troll Coder.py │ ├── JZ 03 数组中重复的数字.py │ ├── JZ 68 - II. 二叉树的最近公共祖先.py │ ├── JZ1 二维数组中的查找.py │ ├── JZ10 矩形覆盖.py │ ├── JZ11 二进制中1的个数.py │ ├── JZ12 数值的整数次方.py │ ├── JZ13 调整数组顺序使奇数位于偶数前面.py │ ├── JZ14 链表中第k个结点.py │ ├── JZ15 反转链表.py │ ├── JZ16 合并两个排序的链表.py │ ├── JZ17 树的子结构.py │ ├── JZ18 二叉树的镜像.pyi │ ├── JZ19 顺时针打印矩阵.py │ ├── JZ20 包含min函数的栈.py │ ├── JZ21 栈的压入、弹出序列.py │ ├── JZ22 从上往下打印二叉树.py │ ├── JZ23 二叉搜索树的后序遍历序列.py │ ├── JZ24 二叉树中和为某一值的路径.py │ ├── JZ25 复杂链表的复制.py │ ├── JZ26 二叉搜索树到双向链表.py │ ├── JZ27 字符串的排列.py │ ├── JZ28 数组中出现次数超过一半的数字.py │ ├── JZ29 最小的K个数.py │ ├── JZ30 连续子数组的最大和.py │ ├── JZ32 整数中1出现的次数(从1到n整数中1出现的次数).py │ ├── JZ33 把数组排成最小的数.py │ ├── JZ33 把数组排成最小的数_functool.py │ ├── JZ34 丑数.py │ ├── JZ35 数组中的逆序对.py │ ├── JZ35 第一个只出现一次的字符.py │ ├── JZ36 数组中的逆序对.py │ ├── JZ37 两个链表的第一个公共结点.py │ ├── JZ38 二叉树的深度.py │ ├── JZ38 数字在排序数组中出现的次数.py │ ├── JZ39 平衡二叉树.py │ ├── JZ4 重建二叉树.py │ ├── JZ40 数组中只出现一次的数字.py │ ├── JZ41 和为S的正整数序列.py │ ├── JZ42 和为S的两个数字.py │ ├── JZ43 左旋字符串.py │ ├── JZ44 翻转字符串序列.py │ ├── JZ45 扑克牌顺子.py │ ├── JZ46 孩子们的游戏.py │ ├── JZ46 数字翻译字符串.py │ ├── JZ47 求1+2+3+...+n.py │ ├── JZ48 不用加减乘除做加法.py │ ├── JZ48 最长不含重复数组的子字符串.py │ ├── JZ49 把字符串转换为整数.py │ ├── JZ5 用两个栈实现队列.py │ ├── JZ50 数组中重复的数字.py │ ├── JZ51 构建乘积数组.py │ ├── JZ52 正则表达式匹配.py │ ├── JZ52 正则表达式的匹配.py │ ├── JZ53 表示数值的字符串.py │ ├── JZ54 字符流中第一个不重复的字符.py │ ├── JZ55 链表中环的入口结点.py │ ├── JZ56 删除链表中重复的结点.py │ ├── JZ57 二叉树的下一个节点.py │ ├── JZ58 对称的二叉树.py │ ├── JZ59 之字形打印二叉树.py │ ├── JZ6 旋转数组的最小数字.py │ ├── JZ60 把二叉树打印成多行.py │ ├── JZ60. n个骰子的点数.py │ ├── JZ61 序列化二叉树.py │ ├── JZ63 二叉搜索树的第k个结点.py │ ├── JZ63 数据流中的中位数.py │ ├── JZ64 滑动窗口中的最大值.py │ ├── JZ65 矩阵中的路径.py │ ├── JZ66 机器人的运动范围.py │ ├── JZ67 剪绳子.py │ ├── JZ7 斐波那契数列.py │ ├── JZ8 跳台阶.py │ ├── JZ9 变态跳台阶.py │ ├── KMP.py │ ├── L.py │ ├── L1007. Minimum Domino Rotations For Equal Row.py │ ├── L102. Binary Tree Level Order Traversal.py │ ├── L103. Binary Tree Zigzag Level Order Traversal.py │ ├── L1036. Escape a Large Maze.py │ ├── L104. Maximum Depth of Binary Tree.py │ ├── L1048. Longest String Chain.py │ ├── L10_RegularMatching.py │ ├── L110. Balanced Binary Tree.py │ ├── L111. Minimum Depth of Binary Tree.py │ ├── L1143 Longest Common Subsequence.py │ ├── L1146. Snapshot Array.py │ ├── L11_containeWithMostWater.py │ ├── L121_BestTimeB%S.py │ ├── L122. Best Time to Buy and Sell Stock II.py │ ├── L128. Longest Consecutive Sequence.py │ ├── L1296. Divide Array in Sets of K Consecutive Numbers.py │ ├── L12_IntegertoRoman.py │ ├── L130. Surrounded Regions.py │ ├── L131. Palindrome Partitioning.py │ ├── L134. Gas Station.py │ ├── L136. Single Number.py │ ├── L137. Single Number II.py │ ├── L1376. Time Needed to Inform All Employees.py │ ├── L139 testcase.txt │ ├── L139_WordBreak.py │ ├── L140. Word Break II.py │ ├── L1401. Circle and Rectangle Overlapping.py │ ├── L141. Linked List Cycle.py │ ├── L142. Linked List Cycle II.py │ ├── L143. Reorder List.py │ ├── L1466. Reorder Routes to Make All Paths Lead to the City Zero.py │ ├── L1470. Shuffle the Array.py │ ├── L1471. The k Strongest Values in an Array.py │ ├── L1472. Design Browser History.py │ ├── L1473. Paint House III.py │ ├── L148. Sort List.py │ ├── L148. sort linked list.py │ ├── L149. Max Points on a Line.py │ ├── L149. Max Points on a Line0811.py │ ├── L14_LongestCommonPrefix.py │ ├── L15. 3Sum.py │ ├── L150. Evaluate Reverse Polish Notation.py │ ├── L152. Maximum Product Subarray.py │ ├── L153. Find Minimum in Rotated Sorted Array.py │ ├── L155_minStack.py │ ├── L155_othermethod.py │ ├── L1562.find latest group of size m.py │ ├── L1563.stone game.py │ ├── L1566. Detect Pattern of Length M Repeated K or More Times.py │ ├── L1567. Maximum Length of Subarray With Positive Product.py │ ├── L1569. Number of Ways to Reorder Array to Get Same BST.py │ ├── L15_3Sum.py │ ├── L160. Intersection of Two Linked Lists.py │ ├── L167. Two Sum II - Input array is sorted.py │ ├── L16_3SumClosest.py │ ├── L174 dungen game.py │ ├── L174_DungenGame.py │ ├── L17_LetterCombinationsofaPhoneNumber.py │ ├── L187. Repeated DNA Sequences.py │ ├── L191. Number of 1 Bits.py │ ├── L1_TwoSum.py │ ├── L200. Number of Islands.py │ ├── L200. Number of Islands_0710.py │ ├── L200. Number of Islands_bfs.py │ ├── L201. Bitwise AND of Numbers Range.py │ ├── L207_CourseSchedule_toposort.py │ ├── L207_CouurseSchedule42ms.py │ ├── L209. Minimum Size Subarray Sum.py │ ├── L20_Valid Parentheses.py │ ├── L210_CouurseScheduleii.py │ ├── L214_Shortest Palindrome.py │ ├── L215. KthLargestElement.py │ ├── L215_KthLargestElement.py │ ├── L216_CombinationSumIII.py │ ├── L216_CombinationSumIII09.py │ ├── L218. the skyline problem.py │ ├── L21_Merge Two Sorted Lists.py │ ├── L22. Generate Parentheses.py │ ├── L221. Maximal Square.py │ ├── L222. Count Complete Tree Nodes.py │ ├── L227. Basic Calculator II.py │ ├── L23. Merge k Sorted Lists.py │ ├── L230. Kth Smallest Element in a BST.py │ ├── L231_PowerOf2.py │ ├── L232_QueueWithStack.py │ ├── L234. Palindrome Linked List.py │ ├── L235. Lowest Common Ancestor of a Binary Search Tree.py │ ├── L236. Lowest Common Ancestor of a Binary Tree.py │ ├── L238. Product of Array Except Self.py │ ├── L23_mergeTree.py │ ├── L240_Search2DMatrixdiscussion.py │ ├── L240_searchA2DMatrix.py │ ├── L241_Different Ways to Add Parentheses.py │ ├── L24_Swap Nodes in Pairs.py │ ├── L25. Reverse Nodes in k-Group.py │ ├── L25. Reverse Nodes in k-Group_0731.py │ ├── L26 Remove Duplicates from Sorted Array.py │ ├── L274_HIndex.py │ ├── L275. H-Index II.py │ ├── L278. First Bad Version.py │ ├── L279. Perfect Squares.py │ ├── L287. Find the Duplicate Number.py │ ├── L289. Game of Life.py │ ├── L290_WordPattern.py │ ├── L295. Find Median from Data Stream.py │ ├── L2_addTwoNumbers.py │ ├── L30. Substring with Concatenation of All Words.py │ ├── L300 Longest Increasing Subsequence.py │ ├── L300 Longest Increasing Subsequence_faster.py │ ├── L307. Range Sum Query - Mutable.py │ ├── L309. Best Time to Buy and Sell Stock with Cooldown.py │ ├── L30_Substring_connectallword.py │ ├── L31. Next Permutation.py │ ├── L315.py │ ├── L32. Longest Valid Parentheses.py │ ├── L322 Coin Change.py │ ├── L324 Wiggle sort II.py │ ├── L327_CountofRangeSum.py │ ├── L328_oddEvenLinkedList.py │ ├── L329. Longest Increasing Path in a Matrix.py │ ├── L33 Search in Rotated Sorted Array.py │ ├── L33. Search in Rotated Sorted Array.py │ ├── L332_BurstBalloon.py │ ├── L337. House Robber III.py │ ├── L338. Counting Bits.py │ ├── L34 Find First and Last Position of Element in Sorted Array.py │ ├── L341. Flatten nested list iterator.py │ ├── L343. Integer Break.py │ ├── L347. Top K Frequent Elements.py │ ├── L354. Russian Doll Envelop.py │ ├── L36 Valid Sudoku.py │ ├── L37 Sudoku Solver.py │ ├── L38 Count and Say.py │ ├── L380. Insert Delete GetRandom O(1).py │ ├── L39 Combination Sum.py │ ├── L392 is subsequence.py │ ├── L394. Decode String.py │ ├── L399 Evaluate division.py │ ├── L399_EvaluateDivision.py │ ├── L3_Longest Substring Without Repeating Characters.py │ ├── L41 First Missing Positive.py │ ├── L410. Split Array Largest Sum.py │ ├── L413. Arithmetic Slices.py │ ├── L416. partition equal subset sum.py │ ├── L42 Trapping Rain Water.py │ ├── L438. Find All Anagrams in a String.py │ ├── L44 Wildcard Matching.py │ ├── L445. Add Two Numbers II.py │ ├── L446_ArithmeticSlicesII-Subsequence.py │ ├── L446_official.py │ ├── L448. Find All Numbers Disappeared in an Array.py │ ├── L45 Jump Game II.py │ ├── L453_MinimumMovestoEqualArrayElements.py │ ├── L46 Permutations.py │ ├── L464_CanIWin.py │ ├── L47 Permutations II.py │ ├── L48 Rotate Image.py │ ├── L49 Group Anagrams.py │ ├── L4_MedianofTwoSortedArrays.py │ ├── L50 Pow(x, n).py │ ├── L509. Fibonacci Number.py │ ├── L51_NQueens.py │ ├── L525. Contiguous Array.py │ ├── L53 Maximum Subarray.py │ ├── L54 Spiral Matrix.py │ ├── L54. Spiral Matrix.py │ ├── L540_SingleElement.py │ ├── L542_01Matrix.py │ ├── L542_matrix_again.py │ ├── L542_matrix_noSearch.py │ ├── L543. Diameter of Binary Tree.py │ ├── L547. Friend Circles.py │ ├── L547_friendcircle.py │ ├── L55 Jump Game.py │ ├── L559_Maximumdepth.py │ ├── L56 Merge Intervals.py │ ├── L57 Insert Interval.py │ ├── L572. Subtree of Another Tree.py │ ├── L57_InsertInterval.py │ ├── L57_InsertIntervals.py │ ├── L58. Length of Last Word.py │ ├── L59. Spiral Matrix II.py │ ├── L5_LongestPalindromicSubstring.py │ ├── L60. Permutation Sequence.py │ ├── L61_Rotate_List_linked_list_debug.py │ ├── L62. Unique Paths.py │ ├── L63. Unique Paths II.py │ ├── L630_CourseScheduleiii.py │ ├── L630_CourseScheduleiiians.py │ ├── L637_AverageVal.py │ ├── L637_AverageValPT.py │ ├── L64. Minimum Path Sum.py │ ├── L648_replaceWord.py │ ├── L66. Plus One.py │ ├── L662_maxWidthinBinaryTree.py │ ├── L67. Add Binary.py │ ├── L670 Maximum Swap.py │ ├── L684_RedundentConnection.py │ ├── L692.top-k-frequent-words.py │ ├── L70_CllimingStairsinDP.py │ ├── L70_climbingStairinCombination.py │ ├── L71. Simplify Path.py │ ├── L718. Maximum Length of Repeated Subarray.py │ ├── L72. Edit Distance.py │ ├── L721. Accounts Merge.py │ ├── L73. Set Matrix Zeroes.py │ ├── L739. Daily Temperatures.py │ ├── L74. Search a 2D Matrix.py │ ├── L743. Network Delay Time.py │ ├── L75. Sort Colors.py │ ├── L752. Open the Lock.py │ ├── L78. Subsets.py │ ├── L784_LetterPermutation.py │ ├── L79. Word Search.py │ ├── L7_reverseInteger.py │ ├── L80. Remove Duplicates from Sorted Array II.py │ ├── L814. Binary Tree Pruning.py │ ├── L82. Remove Duplicates from Sorted List II.py │ ├── L833. Find And Replace in String.py │ ├── L841_Key&Rooms.py │ ├── L84_LargestRect.py │ ├── L84_other.py │ ├── L85 LongerstIncreasingPath.py │ ├── L857. Minimum Cost to Hire K Workers.py │ ├── L876. Middle of the Linked List.py │ ├── L88. Merge Sorted Array.py │ ├── L89. Gray Code.py │ ├── L896_MonotonicArray.py │ ├── L914. X of a Kind in a Deck of Cards.py │ ├── L921. Minimum Add to Make Parentheses Valid.py │ ├── L94. Binary Tree Inorder Traversal.py │ ├── L946. Validate Stack Sequences.py │ ├── L958. Check Completeness of a Binary Tree.py │ ├── L98. Validate Binary Search Tree.py │ ├── L98_test_case.py │ ├── L9_PalindromeNumber.py │ ├── Lemons.py │ ├── Lexical Addition.py │ ├── MS.py │ ├── MS02.py │ ├── MS04.py │ ├── Math_Attack and Speed.py │ ├── Monotonic stack.py │ ├── NC74 牛牛的魔法值 单调栈.py │ ├── ORIENTEERING.py │ ├── Octopuses with Watches.py │ ├── Odd Cycle Check.py │ ├── Pair Swap Teams.py │ ├── Preparing for Xtreme 12.0.py │ ├── Protecting the Hive.py │ ├── Read Input.py │ ├── Strictly Convex Pairs.py │ ├── Strong connected component Shuffle.py │ ├── Threading.py │ ├── TopoSort.py │ ├── Two Pointers_Cities Robbery.py │ ├── UnionFind.py │ ├── WeekContest2.py │ ├── Xplore.py │ ├── Xtreme Rappers.py │ ├── Xtreme13.Alfa Pool.py │ ├── Xtreme13.Barter system.py │ ├── Xtreme13.Batchman and GCD.py │ ├── Xtreme13.Factorial zeros.py │ ├── Xtreme13.Luck-i-flip.py │ ├── Xtreme13.Math challenge.py │ ├── Xtreme13.Monokeros.py │ ├── Xtreme13.Pirates.py │ ├── Xtreme13.Product Rectangle.py │ ├── Xtreme13.Quipu function.py │ ├── Xtreme13.Ranged Alfa Pool.py │ ├── Xtreme13.Strictly Convex Pairs.py │ ├── Xtreme13.Telescope scheduling.py │ ├── Xtreme13.Tree Fun.py │ ├── Xtreme13.Unicornosaurus.py │ ├── Xtreme13.bearcity renting.py │ ├── Xtreme13.googloplex.py │ ├── Xtreme13.protecting the hive.py │ ├── Xtreme13The Lonely Shepherd.py │ ├── Yin Yang.py │ ├── baidu01.py │ ├── bit manipulation RecXor.py │ ├── blacklist.TXT │ ├── contest02.py │ ├── contest03.py │ ├── contest04.py │ ├── cross entropy.py │ ├── decorator.py │ ├── didi.py │ ├── dijksta Algor adj list.py │ ├── dijksta Algor print path.py │ ├── filpGame.py │ ├── heap sort.py │ ├── in.txt │ ├── kuangshi02.py │ ├── lqw.py │ ├── manacher.py │ ├── multiProcessing.py │ ├── multiProcessingVSmthreading.py │ ├── myDFS.py │ ├── mylist.py │ ├── new.py │ ├── newfile.py │ ├── priorityQueue.py │ ├── property&setter.py │ ├── rotate image.py │ ├── tenary search.py │ ├── tencent 翻转数组的前n项和.py │ ├── test.py │ ├── topological sort+DETECT CIRCLE.py │ ├── ttees.py │ ├── ziji04.py │ ├── zijie02.py │ ├── zijie02new.py │ ├── zijie082301.py │ ├── zijie1011.py │ ├── 剑指 Offer 68 - II. 二叉树的最近公共祖先.py │ ├── 协程.py │ ├── 面试题 02.06. Palindrome Linked List LCCI.py │ ├── 面试题 03.05. Sort of Stacks LCCI.py │ └── 面试题 03.05. Sort of Stacks LCCI_stack.py ├── README.ipynb └── README.md ├── 05_Language ├── README.ipynb └── README.md ├── 06_DL_framework ├── README.ipynb └── README.md ├── 07_Interview_Questions ├── Pics │ ├── CEderivative.png │ ├── Directionalderivative.svg │ ├── FCN.jpg │ ├── GB.png │ ├── KKT.png │ ├── MSEderivative.png │ ├── SVM.png │ ├── Segnet.jpg │ ├── Unet.jpg │ ├── Untitled 1.png │ ├── Untitled 2.png │ ├── Untitled 3.png │ ├── Untitled 4.png │ ├── Untitled 5.png │ ├── Untitled 6.png │ ├── Untitled 7.png │ ├── Untitled.png │ ├── basicbottle.jpg │ ├── cascade-RCNN.png │ ├── complementary.png │ ├── convCompute.png │ ├── deeplabv3.png │ ├── detection.jpg │ ├── detrans.png │ ├── dialated.gif │ ├── dp_0.png │ ├── dp_1.jpg │ ├── dropconnect.png │ ├── dropout.png │ ├── equation1.svg │ ├── equation2.svg │ ├── gk.png │ ├── harris.svg │ ├── hough.jpg │ ├── inout.png │ ├── laplace.png │ ├── laplace.svg │ ├── laplace_e.jpg │ ├── max_pooling.jpeg │ ├── mean_pooling.jpeg │ ├── mr_f1.png │ ├── n.png │ ├── overlap.jpg │ ├── psp.png │ ├── receptive_field.svg │ ├── relu.png │ ├── samplebias.jpg │ ├── sobel.jpg │ ├── sobel_2.jpg │ ├── softmargin.png │ ├── stacking.png │ ├── transequa.png │ ├── transposed.png │ └── transposed_result.gif ├── README.ipynb └── README.md ├── README.ipynb ├── README.md └── Utils ├── AddAnchor.ipynb └── utils.py /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | .ipynb_checkpoints/ 3 | 01_Math/.ipynb_checkpoints/ 4 | 02_ML_knowledge/.ipynb_checkpoints/ 5 | 03_DL_knowledge/.ipynb_checkpoints/ 6 | 04_Algorithms/.ipynb_checkpoints/ 7 | 05_Language/.ipynb_checkpoints/ 8 | 06_DL_framework/.ipynb_checkpoints/ 9 | 07_Interview_Questions/.ipynb_checkpoints/ 10 | Utils/__pycache__/ 11 | 04_Algorithms/Leetcode/__pycache__/ 12 | 04_Algorithms/Leetcode/WeekContest1.py 13 | 04_Algorithms/Leetcode/ieee01.py 14 | -------------------------------------------------------------------------------- /01_Math/Pics/bayesian.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/01_Math/Pics/bayesian.png -------------------------------------------------------------------------------- /01_Math/README.md: -------------------------------------------------------------------------------- 1 | # 数学知识:矩阵理论,概率论等 2 | * 2.线性代数 3 | * 2.1 标量,向量,矩阵和张量 4 | * 2.2 矩阵和向量相乘: 5 | * 2.3 单位矩阵和逆矩阵: 6 | * 2.4 线性相关和生成子空间: 7 | * 2.5 范数:衡量向量大小的函数 8 | 9 | * 3.概率和信息论 10 | 11 | * 4.数值计算 12 | * 4.1 上溢和下溢 13 | * 4.2 病态条件 14 | * 4.3基于梯度的优化方法 15 | * 4.3.1 雅可比和海森矩阵 16 | 17 | -------------------------------------------------------------------------------- /02_ML_knowledge/Pics/bayesian.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/02_ML_knowledge/Pics/bayesian.png -------------------------------------------------------------------------------- /02_ML_knowledge/Pics/cluster.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/02_ML_knowledge/Pics/cluster.png -------------------------------------------------------------------------------- /02_ML_knowledge/Pics/cluster2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/02_ML_knowledge/Pics/cluster2.jpg -------------------------------------------------------------------------------- /02_ML_knowledge/README.md: -------------------------------------------------------------------------------- 1 | # 机器学习知识总结 2 | 李航机器学习整理+ [this repo](https://github.com/shiyutang/MachineLearning)+ [shuhuai 的白板推导视频](https://www.bilibili.com/video/BV1aE411o7qd?p=2) 3 | 4 | 5 | * [1. 频率派和贝叶斯派](#1.频率派和贝叶斯派) 6 | * 频率派 7 | * 贝叶斯派 8 | 9 | * [2. 聚类](#2.聚类) 10 | * 聚集派 11 | * 连接派 12 | 13 | * [3. 降维](#3.降维) 14 | * PCA 15 | * SVD 16 | -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/ALEX.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/ALEX.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/Conjugate_gradient_illustration.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/Conjugate_gradient_illustration.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/MLE1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/MLE1.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/MLE2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/MLE2.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/NIN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/NIN.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/Nesterov.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/Nesterov.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/Nesterovshow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/Nesterovshow.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/Nesterovshow2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/Nesterovshow2.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/OVERFIT.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/OVERFIT.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/SENET.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/SENET.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/SGDupdate.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/SGDupdate.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/Uniform.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/Uniform.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/VGG.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/VGG.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/activation.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/activation.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/conv.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/conv.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/convbias.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/convbias.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/convdia.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/convdia.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/convexset.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/convexset.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/convmulc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/convmulc.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/convsize.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/convsize.gif -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/convstruct.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/convstruct.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/corr.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/corr.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/cross_ent.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/cross_ent.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/densenet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/densenet.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/densenetjump.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/densenetjump.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/dropout.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/dropout.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/fc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/fc.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/gconv.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/gconv.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/googlenet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/googlenet.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/googlenet_full.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/googlenet_full.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/lenet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/lenet.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/linearloss.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/linearloss.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/loss_reg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/loss_reg.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/minmul.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/minmul.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/minmulcal.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/minmulcal.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/minmulexp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/minmulexp.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/poolgrad.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/poolgrad.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/residual.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/residual.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/senetres.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/senetres.png -------------------------------------------------------------------------------- /03_DL_knowledge/Pics/softmax.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/03_DL_knowledge/Pics/softmax.png -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/0-1 knapsack.py: -------------------------------------------------------------------------------- 1 | def knapsack(C, value_list, weight_list): 2 | """ 3 | C : 背包容量 4 | value_list : 商品价值列表 5 | weight_list :商品重量列表 6 | 7 | """ 8 | n = len(value_list) 9 | dp = [[0 for _ in range(C + 1)] for __ in range(n + 1)] 10 | for i in range(1, n + 1): 11 | for j in range(1, C + 1): 12 | # 如果当前背包容量还够装下当前商品 13 | if j >= weight_list[i - 1]: 14 | dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight_list[i - 1]] + value_list[i - 1]) 15 | else: 16 | dp[i][j] = dp[i - 1][j] 17 | return dp[n][C] 18 | 19 | 20 | # test 21 | import random 22 | 23 | test_time = 20 24 | for _ in range(test_time): 25 | C = random.randint(0, 100) 26 | items = random.randint(1, 20) 27 | 28 | valueL, weightL = [], [] 29 | for _ in range(items): 30 | valueL.append(random.randint(0, 10)) 31 | weightL.append(random.randint(1, 20)) 32 | 33 | res = knapsack(C, valueL, weightL) 34 | print("The knapsack with volume {} will contain items " 35 | "worth {} when values are {} and weights are {}".format(C, res, valueL, weightL)) 36 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/011.py: -------------------------------------------------------------------------------- 1 | def solve(start, end): 2 | start.sort() 3 | end.sort() 4 | cnt = 0 5 | maxval = 0 6 | s, e = 0, 0 7 | while s < len(start): 8 | if start[s] < end[e]: 9 | cnt += 1 10 | maxval = max(maxval, cnt) 11 | s += 1 12 | else: 13 | cnt -= 1 14 | e += 1 15 | print(maxval) 16 | 17 | 18 | while 1: 19 | try: 20 | n = int(input()) # 去除首尾空格 21 | start, end = [], [] 22 | for i in range(int(n)): 23 | line = input().split() # 返回分割好的字符列表 24 | start.append(int(line[0])) 25 | end.append(int(line[1])) 26 | 27 | solve(start, end) 28 | except: 29 | break 30 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/0827.py: -------------------------------------------------------------------------------- 1 | import copy 2 | 3 | 4 | def bisect(data, target): 5 | """ 6 | :param data: list in ascending order 7 | :param target: 8 | :return: 9 | """ 10 | data.sort() 11 | low, high = 0, len(data) - 1 12 | mid = int((high - low) / 2 + low) 13 | 14 | while low < high: 15 | if data[mid] == target: 16 | return midw 17 | elif data[mid] > target: 18 | high = mid 19 | else: 20 | low = mid + 1 21 | mid = int((high - low) / 2 + low) 22 | 23 | return mid 24 | 25 | 26 | data = [1, 2, 3, 4, 5, 6, 7, 9] 27 | print(data[bisect(data, 5)]) 28 | 29 | a = [1, 2, [4, 5], [2, 3, 43]] 30 | 31 | c = a[:] 32 | d = copy.deepcopy(a) 33 | d[2][1] = 100 34 | print(d, a) 35 | c[2][1] = 100 36 | print(c, a) 37 | 38 | shallow = a 39 | shallow[2] = 1000 40 | print(shallow, a) 41 | 42 | a = iter([1, 2, 3]) 43 | for i in a: 44 | print(i) 45 | for i in a: 46 | print(i) 47 | c = (1, 2, 3) 48 | for i in c: 49 | print(i) 50 | for i in c: # 只能使用一次 51 | print(i) 52 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/2.3 Cnk.py: -------------------------------------------------------------------------------- 1 | # 使用 Pascal 递推公式计算,有点慢 2 | 3 | import collections 4 | 5 | 6 | def choose_k_from_n(n, k): 7 | """求取组合数(n, k)""" 8 | C = collections.defaultdict(int) 9 | for row in range(n + 1): 10 | C[row, 0] = 1 11 | print(C) 12 | for col in range(1, min(row + 1, k + 1)): 13 | C[row, col] = C[row - 1, col - 1] + C[row - 1, col] # 递推公式,同时保存运算结果 14 | print(C) 15 | return C[n, k] 16 | 17 | 18 | print(choose_k_from_n(10, 3)) 19 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/Ad-Hoc_move the bishop.py: -------------------------------------------------------------------------------- 1 | def parser(): 2 | while 1: 3 | data = list(input().split(' ')) 4 | for number in data: 5 | if len(number) > 0: 6 | yield (number) 7 | 8 | 9 | input_parser = parser() 10 | 11 | 12 | def get_word(): 13 | global input_parser 14 | return next(input_parser) 15 | 16 | 17 | def get_number(): 18 | data = get_word() 19 | try: 20 | return int(data) 21 | except ValueError: 22 | return float(data) 23 | 24 | 25 | R1, C1, R2, C2 = get_number(), get_number(), get_number(), get_number() 26 | rowDiff = abs(R2 - R1) 27 | if C2 == C1 and rowDiff == 0: 28 | res = 0 29 | else: 30 | C1tmp = [C1 - rowDiff, C1 + rowDiff][C2 > C1] 31 | if C2 == C1tmp: 32 | res = 1 33 | elif (C2 - C1tmp) % 2 == 0: 34 | res = 2 35 | else: 36 | res = -1 37 | 38 | print(res) 39 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/B01.py: -------------------------------------------------------------------------------- 1 | def solution(A): 2 | count, idx = 0, 0 3 | 4 | while A[idx] != -1: 5 | value = A[idx] 6 | idx = value 7 | count += 1 8 | count += 1 9 | return count 10 | 11 | 12 | sol = solution([1, 4, -1, 3, 2]) 13 | print(sol) 14 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/BFS.py: -------------------------------------------------------------------------------- 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 | def canVisitAllRooms(self, root): 9 | queue = [root] 10 | mark = [root] #already visited place 11 | while queue: 12 | node,width = queue.pop(0) 13 | # print(idx) 14 | for child in [root.left,root.right]: # ALL NEIGHBOR 15 | if not child in mark: 16 | queue.append(child) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/Binary Search_Strange Distance.py: -------------------------------------------------------------------------------- 1 | # a simple parser for python. use get_number() and get_word() to read 2 | def parser(): 3 | while 1: 4 | data = list(input().split(' ')) 5 | for number in data: 6 | if len(number) > 0: 7 | yield(number) 8 | 9 | input_parser = parser() 10 | 11 | def get_word(): 12 | global input_parser 13 | return next(input_parser) 14 | 15 | def get_number(): 16 | data = get_word() 17 | try: 18 | return int(data) 19 | except ValueError: 20 | return float(data) 21 | 22 | # read input 23 | N,K = get_number(),get_number() 24 | point = [] 25 | for i in range(N): 26 | x,y = get_number(),get_number() 27 | point.append((x,y)) 28 | keepRecord = [] 29 | for i in range(len(point)-1): 30 | for j in range(i+1,len(point)): 31 | dis = min((abs(point[i][0]-point[j][0]),abs(point[i][1]-point[j][1]))) 32 | keepRecord.append(dis) 33 | 34 | keepRecord.sort() 35 | print(keepRecord[K-1]) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/ConstructGraph.py: -------------------------------------------------------------------------------- 1 | # class edge: 2 | # def __init__(self,ID): 3 | # self.id = ID 4 | # self.to = None 5 | # self.nextID = None 6 | 7 | adjMat = [[0,7,1000*100,5,1000*100,1000*100,1000*100], 8 | [1000*100,0,8,9,7,1000*100,1000*100], 9 | [1000*100,1000*100,0,1000*100,5,1000*100,1000*100], 10 | [1000*100,1000*100,1000*100,0,15,6,1000*100], 11 | [1000*100,1000*100,1000*100,1000*100,0,8,9], 12 | [1000*100,1000*100,1000*100,1000*100,1000*100,0,11], 13 | [1000*100,1000*100,1000*100,1000*100,1000*100,1000*100,0]] 14 | 15 | LE = [-1]*len(adjMat) 16 | edges = [] 17 | k = 0 18 | for i in range(len(adjMat)): 19 | for weight in adjMat[i]: 20 | if weight >0 and weight<10*10: 21 | newedge = [k,-1,-1] 22 | newedge[1] = adjMat[i].index(weight) 23 | newedge[2] = LE[i] 24 | edges.append(newedge) 25 | LE[i] = k 26 | k += 1 27 | 28 | print(LE) 29 | print(edges) 30 | 31 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/Infinite String.py: -------------------------------------------------------------------------------- 1 | # a simple parser for python. use get_number() and get_word() to read 2 | def parser(): 3 | while 1: 4 | data = list(input().split(' ')) 5 | for number in data: 6 | if len(number) > 0: 7 | yield(number) 8 | 9 | input_parser = parser() 10 | 11 | def get_word(): 12 | global input_parser 13 | return next(input_parser) 14 | 15 | def get_number(): 16 | data = get_word() 17 | try: 18 | return int(data) 19 | except ValueError: 20 | return float(data) 21 | 22 | # numpy and scipy are available for use 23 | import numpy 24 | import scipy 25 | 26 | numTest = get_number() 27 | for i in range(numTest): 28 | numAlphabet,queIdx = get_number(),get_number()+1 29 | 30 | blocknum,res = 1,0 31 | while res int: 6 | memoi = set() 7 | for i, num in enumerate(nums): 8 | if num in memoi: 9 | return num 10 | else: 11 | memoi.add(num) 12 | 13 | 14 | sol = Solution() 15 | print(sol.findRepeatNumber([2, 1, 3, 3])) 16 | # print(sol.findRepeatNumber([])) 17 | # print(sol.findRepeatNumber([2, 1, 3, 1, 4, 5])) 18 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ1 二维数组中的查找.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # 想利用三次二分是不靠谱的,因为大于上面一行某一列的不一定就大于这一列所有的值 3 | # 方法: 设置一个关键节点,这个节点处在大于和小于的中间,类似于mid节点,那么根据大于还是小于就知道怎么判断 4 | # 这个节点可以是右上角也可以是左下角 5 | class Solution: 6 | # array 二维列表 7 | def Find(self, target, array): 8 | if array == [[]] or array == []: 9 | return False 10 | i, j = 0, len(array[0]) - 1 11 | val = array[i][j] 12 | 13 | def isvalid(row, col): 14 | return 0 <= row < len(array) and 0 <= col < len(array[0]) 15 | 16 | while 1: 17 | if target > val: 18 | i += 1 19 | elif target == val: 20 | return True 21 | else: 22 | j -= 1 23 | if not isvalid(i, j): 24 | return False 25 | val = array[i][j] 26 | # print(i, j) 27 | 28 | 29 | sol = Solution() 30 | print(sol.Find(10, [[1, 2, 3, 4], 31 | [2, 6, 7, 9], 32 | [5, 10, 11, 12], ])) 33 | print(sol.Find(10, [[1, 2, 3, 4], 34 | [2, 9, 11, 13], 35 | [5, 10, 11, 12], ])) 36 | print(sol.Find(10, [[]])) 37 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ10 矩形覆盖.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # 动态规划,为n的是为n-1和为n-2的组合,这个memoi也可以不需要,因为是前两项的之和 3 | class Solution: 4 | def __init__(self): 5 | self.memoi = {1: 1, 2: 2} 6 | 7 | def rectCover(self, number): 8 | if number < 1: 9 | return 0 10 | elif number in self.memoi: 11 | return self.memoi[number] 12 | else: 13 | res = self.rectCover(number - 1) + self.rectCover(number - 2) 14 | self.memoi[number] = res 15 | return res 16 | 17 | 18 | sol = Solution() 19 | print(sol.rectCover(300)) 20 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ11 二进制中1的个数.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | def NumberOf1(self, n): 4 | cnt = 0 5 | mark = 0x01 6 | for _ in range(32): 7 | if mark & n: 8 | cnt += 1 9 | mark <<= 1 10 | return cnt 11 | 12 | # method2: val 每次和自己的减一相与就会少一个1,一直到val为0 即可 13 | 14 | 15 | sol = Solution() 16 | print(sol.NumberOf1(-1)) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ12 数值的整数次方.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | def Power(self, base, exponent): 4 | if exponent < 0: 5 | if base == 0: 6 | return 7 | else: 8 | base = 1 / base 9 | exponent = -exponent 10 | 11 | def fastpow(a, b): 12 | if b == 1: 13 | return a 14 | elif b == 0: 15 | return 1 16 | 17 | if b % 2 == 0: 18 | res = fastpow(a * a, b // 2) 19 | else: 20 | res = a * fastpow(a * a, b // 2) 21 | return res 22 | 23 | return fastpow(base, exponent) 24 | 25 | 26 | sol = Solution() 27 | print(sol.Power(2, -3)) 28 | print(sol.Power(2, 0)) 29 | print(sol.Power(0, 1)) 30 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ13 调整数组顺序使奇数位于偶数前面.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # 指定一个插入奇数的指针,每次插入为O(1), 插入了之后指针前移即可 3 | class Solution: 4 | def reOrderArray(self, array): 5 | oddidx = 0 6 | for idx, num in enumerate(array): 7 | if num % 2 == 1: 8 | array.pop(idx) 9 | array.insert(oddidx, num) 10 | oddidx += 1 11 | # print(num,array) 12 | return array 13 | 14 | 15 | sol = Solution() 16 | print(sol.reOrderArray([1, 3, 5, 6, 7])) 17 | print(sol.reOrderArray([])) 18 | print(sol.reOrderArray([1])) 19 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ14 链表中第k个结点.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | # 法 2 严格O(N):快慢指针 快指针先往前走k步,注意判断边界,然后快慢一起走,当快指针为none的时候,慢指针走到了倒数第k个节点 8 | class Solution: 9 | def FindKthToTail(self, head, k): 10 | if not head: 11 | return 12 | else: 13 | cnt = 0 14 | tmp = head 15 | while tmp: 16 | cnt += 1 17 | tmp = tmp.next 18 | if cnt < k: 19 | return 20 | else: 21 | idx = cnt - k 22 | cnt = 0 23 | tmp = head 24 | while cnt < idx: 25 | tmp = tmp.next 26 | cnt += 1 27 | return tmp 28 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ16 合并两个排序的链表.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class ListNode: 3 | def __init__(self, x): 4 | self.val = x 5 | self.next = None 6 | 7 | class Solution: 8 | # 返回合并后列表 9 | def Merge(self, pHead1, pHead2): 10 | if not pHead1: 11 | return pHead2 12 | elif not pHead2: 13 | return pHead1 14 | else: 15 | tmp1 = pHead1 16 | tmp2 = pHead2 17 | dummy = ListNode(0) 18 | pointer = dummy 19 | while tmp1 and tmp2: 20 | if tmp1.val < tmp2.val: 21 | pointer.next = tmp1 22 | tmp1 = tmp1.next 23 | else: 24 | pointer.next = tmp2 25 | tmp2 = tmp2.next 26 | pointer = pointer.next 27 | if tmp1: 28 | pointer.next = tmp1 29 | if tmp2: 30 | pointer.next = tmp2 31 | 32 | return dummy.next 33 | 34 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ18 二叉树的镜像.pyi: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class TreeNode: 3 | def __init__(self, x): 4 | self.val = x 5 | self.left = None 6 | self.right = None 7 | 8 | # 也可以在后序遍历中对根进行操作,这里使用层次遍历的方式,后序遍历同理 9 | class Solution: 10 | # 返回镜像树的根节点 11 | def Mirror(self, root): 12 | if not root: 13 | return root 14 | else: 15 | queue = [root] 16 | while queue: 17 | node = queue.pop() 18 | for nei in (node.left,node.right): 19 | if nei: 20 | queue.append(nei) 21 | node.left, node.right =node.right, node.left 22 | return root 23 | 24 | 25 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ20 包含min函数的栈.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | def __init__(self): 4 | self.minval = [] 5 | self.stack = [] 6 | 7 | def push(self, node): 8 | self.stack.append(node) 9 | if not self.minval: 10 | self.minval = [node] 11 | else: 12 | self.minval.append(min(self.minval[-1], node)) 13 | 14 | def pop(self): 15 | val = self.stack.pop(-1) 16 | self.minval.pop(-1) 17 | return val 18 | 19 | def top(self): 20 | return self.stack[-1] 21 | 22 | def min(self): 23 | return self.minval[-1] 24 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ21 栈的压入、弹出序列.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # 根据pop的顺序确定第一个压入栈的元素,之后我们不能直接pop在其之前压入的元素 3 | 4 | class Solution: 5 | def IsPopOrder(self, pushV, popV): # 还有可能pop和push中元素不相等的情况 6 | if set(pushV) != set(popV): 7 | return False 8 | 9 | pre = -1 10 | while popV: 11 | val = popV.pop(0) 12 | idx = pushV.index(val) 13 | if pre == -1: 14 | pre = idx 15 | pushV.pop(idx) 16 | else: 17 | if idx < pre - 1: 18 | return False 19 | else: 20 | pre = idx 21 | pushV.pop(idx) 22 | return True 23 | 24 | 25 | def test(method, random_samples=False): 26 | sol = method() 27 | # data = [1, 2, 3, 4, 5], [5, 4, 3, 2, 1] 28 | # data = [1, 2, 3, 4, 5], [4, 3, 2, 1, 5] 29 | data = [1, 2, 3, 4, 5], [4, 5, 3, 1, 2] 30 | data = [0, 1, 2, 3, 5, 4], [3, 2, 1, 0, 4, 5] 31 | data = [1, 2, 3, 4, 5], [4, 5, 3, 2, 1] 32 | # data = [2, 1, 3, 0], [1, 0, 3, 2] 33 | res = sol.IsPopOrder(data[0], data[1]) 34 | print(res) 35 | 36 | 37 | test(Solution, False) 38 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ26 二叉搜索树到双向链表.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class TreeNode: 3 | def __init__(self, x): 4 | self.val = x 5 | self.left = None 6 | self.right = None 7 | 8 | 9 | class Solution: 10 | def Convert(self, pRootOfTree): 11 | if not pRootOfTree: 12 | return 13 | else: 14 | def helper(node, prev): 15 | if not node: 16 | return prev 17 | prev = helper(node.left, prev) 18 | 19 | prev.right = node 20 | if prev != dummyroot: 21 | node.left = prev 22 | 23 | prev = helper(node.right, node) 24 | 25 | return prev 26 | 27 | dummyroot = TreeNode(0) 28 | _ = helper(pRootOfTree, dummyroot) 29 | return dummyroot.right 30 | 31 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ27 字符串的排列.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | import copy 3 | 4 | 5 | # 排列就是每次选择一位放在前面,之后的继承 6 | class Solution: 7 | def Permutation(self, ss): 8 | memoi = set() 9 | if not ss: 10 | return '' 11 | else: 12 | def helper(string, pt): 13 | if len(string) == pt + 1: 14 | memoi.add(string) 15 | else: 16 | helper(string, pt + 1) 17 | for i in range(pt+1, len(string)): 18 | tmp = copy.deepcopy(string) # swap string 19 | tmp = tmp[:pt] + tmp[i] + tmp[pt + 1:i] + tmp[pt] + tmp[i + 1:] 20 | 21 | helper(tmp, pt + 1) 22 | 23 | helper(ss, pt=0) 24 | ret = list(memoi) 25 | ret.sort() 26 | return ret 27 | 28 | 29 | sol = Solution() 30 | print(sol.Permutation('abc')) 31 | print(sol.Permutation('')) 32 | print(sol.Permutation('aabc')) 33 | print(sol.Permutation('a')) 34 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ29 最小的K个数.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | import bisect 3 | 4 | 5 | class Solution: 6 | def GetLeastNumbers_Solution(self, tinput, k): 7 | if k > len(tinput) or k == 0: # 变量的长度范围要考虑清楚 8 | return [] 9 | package = tinput[:k] 10 | package.sort() 11 | for i in range(k, len(tinput)): 12 | if tinput[i] < package[-1]: 13 | idx = bisect.bisect_left(package, tinput[i]) 14 | package.insert(idx, tinput[i]) 15 | package = package[:k] 16 | return package 17 | 18 | 19 | sol = Solution() 20 | print(sol.GetLeastNumbers_Solution([4, 5, 1, 6, 2, 7, 3, 8], 4)) 21 | 22 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ30 连续子数组的最大和.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # 时间复杂度 O(N) 空间复杂度 O(1) 3 | class Solution: 4 | def FindGreatestSumOfSubArray(self, array): 5 | if not array: 6 | return 7 | p1, p2 = -1, -1 8 | maxval = -float('inf') 9 | for idx, num in enumerate(array): 10 | if p1 < 0 and p2 < 0: 11 | if num > 0: 12 | p1, p2 = idx, idx 13 | sum = num 14 | elif p1 >= 0 and p2 >= 0: 15 | sum += num 16 | if sum > 0: 17 | p2 += 1 18 | else: 19 | p1 = p2 + 1 20 | p2 = p2 + 1 21 | sum = 0 22 | maxval = max(maxval, sum) 23 | # print(idx, p1, p2, sum, maxval) 24 | return maxval 25 | 26 | # 也可以使用动态规划,记录某个 idx 之前的最优情况,看加上当前元素是否还是最优 27 | 28 | 29 | sol = Solution() 30 | print(sol.FindGreatestSumOfSubArray([6, -3, -2, 7, -15, 1, 2, 2])) 31 | print(sol.FindGreatestSumOfSubArray([-3, -2, -1, -15])) 32 | print(sol.FindGreatestSumOfSubArray([-3, -2, -1, -15, 1])) 33 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ32 整数中1出现的次数(从1到n整数中1出现的次数).py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | def NumberOf1Between1AndN_Solution(self, n): 4 | tmp = list(str(n)) 5 | memoi = {1: 1, 20: 10} 6 | for i in range(len(tmp) - 1, -1, -1): 7 | pass 8 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ34 丑数.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # 每次在现有丑数的基础上,乘以2,3,5,找到最小的丑数 3 | class Solution: 4 | def GetUglyNumber_Solution(self, index): 5 | Uglys = [1] 6 | p1, p2, p3 = 0, 0, 0 # 每次记录上一个乘以 x 的位置,乘了其他数的不着急乘,先乘没乘过的 7 | if index < 0: 8 | return 9 | elif index == 0: 10 | return 0 11 | else: 12 | while len(Uglys) < index: 13 | minres = min(Uglys[p1] * 2, min(Uglys[p2] * 3, Uglys[p3] * 5)) 14 | if Uglys[p1] * 2 == minres: 15 | p1 += 1 16 | if Uglys[p2] * 3 == minres: 17 | p2 += 1 18 | if Uglys[p3] * 5 == minres: 19 | p3 += 1 20 | Uglys.append(minres) 21 | return Uglys[-1] 22 | 23 | 24 | sol = Solution() 25 | print(sol.GetUglyNumber_Solution(15)) 26 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ35 第一个只出现一次的字符.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | def __init__(self): 4 | self.str = [] 5 | self.times = [] 6 | 7 | # 返回对应char 8 | def FirstNotRepeatingChar(self, s): 9 | for char in s: 10 | if char in self.str: 11 | self.times[self.str.index(char)] += 1 12 | else: 13 | self.str.append(char) 14 | self.times.append(1) 15 | 16 | try: 17 | idx = self.times.index(1) 18 | return s.index(self.str[idx]) 19 | 20 | except ValueError: 21 | return -1 22 | 23 | 24 | sol = Solution() 25 | print(sol.FirstNotRepeatingChar('google')) 26 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ36 数组中的逆序对.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | import copy 3 | 4 | 5 | class Solution: 6 | def InversePairs(self, data): 7 | pass 8 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ38 二叉树的深度.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | class Solution: 8 | def TreeDepth(self, pRoot): 9 | # write code here 10 | def helper(node, depth): 11 | if not node: 12 | return depth 13 | else: 14 | ret = max(helper(node.right, depth + 1), helper(node.left, depth + 1)) 15 | return ret 16 | 17 | if not pRoot: 18 | return 0 19 | else: 20 | return max(helper(pRoot.left, 1), helper(pRoot.right, 1)) 21 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ4 重建二叉树.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class TreeNode: 3 | def __init__(self, x): 4 | self.val = x 5 | self.left = None 6 | self.right = None 7 | 8 | 9 | # noinspection PyUnboundLocalVariable 10 | # 只需要根据前/后序遍历找到根节点,然后利用根节点将中序遍历分割,再一次递归地传入就可以 11 | class Solution: 12 | # 返回构造的TreeNode根节点 13 | def reConstructBinaryTree(self, pre, tin): 14 | def helper(preOrder, inOrder): 15 | if not preOrder or not inOrder: 16 | return 17 | elif len(preOrder) == 1: 18 | return TreeNode(preOrder[0]) 19 | else: 20 | node = TreeNode(preOrder[0]) 21 | for idx, num in enumerate(inOrder): 22 | if preOrder[0] == num: 23 | bp = idx 24 | break 25 | node.left = helper(preOrder[1:bp + 1], inOrder[:bp]) 26 | node.right = helper(preOrder[bp + 1:], inOrder[bp + 1:]) 27 | return node 28 | 29 | root = helper(pre, tin) 30 | return root 31 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ41 和为S的正整数序列.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | from math import ceil 3 | 4 | # 5 | class Solution: 6 | def FindContinuousSequence(self, tsum): 7 | # 奇数个是tsum整除个数,偶数个是tsum除得有x.5 8 | res = [] 9 | for i in range(2, tsum): 10 | if (i % 2 == 0 and tsum % i == 0.5 * i) or (i % 2 == 1 and tsum % i == 0): 11 | start = ceil(tsum / i) - i // 2 12 | if start > 0: 13 | res.append([start + i for i in range(i)]) 14 | 15 | res.sort(key=lambda s: s[0]) 16 | return res 17 | 18 | 19 | sol = Solution() 20 | print(sol.FindContinuousSequence(3)) 21 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ42 和为S的两个数字.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def FindNumbersWithSum(self, array, tsum): 3 | if not array: 4 | return [] 5 | head, tail = 0, len(array) - 1 6 | while head < tail: 7 | while tsum - array[head] < array[tail]: 8 | tail -= 1 9 | if tsum - array[head] == array[tail]: 10 | return array[head], array[tail] 11 | else: 12 | head += 1 13 | return [] 14 | 15 | 16 | sol = Solution() 17 | print(sol.FindNumbersWithSum([1, 2, 4, 7, 11, 15], 15)) 18 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ43 左旋字符串.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | def LeftRotateString(self, s, n): 4 | if not s: 5 | return '' 6 | sLen = len(s) 7 | idx = n % sLen 8 | return s[idx:] + s[:idx] 9 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ44 翻转字符串序列.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | def ReverseSentence(self, s): 4 | if not s: 5 | return "" 6 | slist = s.split(' ') 7 | res = '' 8 | for idx, item in enumerate(slist[::-1]): 9 | res += item 10 | if idx < len(slist)-1: 11 | res +=' ' 12 | 13 | return res 14 | 15 | sol = Solution() 16 | print(sol.ReverseSentence('student. am I')) 17 | print(sol.ReverseSentence("I am a student.")) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ45 扑克牌顺子.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | from collections import Counter 3 | 4 | 5 | class Solution: 6 | def IsContinuous(self, numbers): 7 | if not numbers: 8 | return False 9 | cont = Counter(numbers) 10 | nbrzeros = cont[0] 11 | numbers.sort() 12 | print(numbers) 13 | diff = [] 14 | for idx in range(nbrzeros+1, len(numbers)): 15 | diff.append(numbers[idx] - numbers[idx - 1] - 1) 16 | 17 | if -1 in diff: 18 | return False 19 | print(diff) 20 | return sum(diff) <= nbrzeros 21 | 22 | 23 | sol = Solution() 24 | # print(sol.IsContinuous([1, 3, 2, 6, 4])) 25 | print(sol.IsContinuous([0, 3, 2, 6, 4])) 26 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ47 求1+2+3+...+n.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | def Sum_Solution(self, n): 4 | return ((1+n)*n)/2 -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ48 不用加减乘除做加法.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def Add(self, num1, num2): 3 | res = (num1 ^ num2) & 0xffffffff # 关注一开始输入的负数 4 | while num2 != 0: 5 | res = (num1 ^ num2) & 0xffffffff 6 | cin = ((num1 & num2) << 1) & 0xffffffff # 保留进位的负数 7 | num2 = cin 8 | num1 = res 9 | # print(num1, num2, cin, res) 10 | 11 | if (res & 0x80000000) >> 31 == 1: # 和32位的16进制数判断是否是负数 12 | res = -(((~res) + 1) & 0xffffffff) # 负数要取反加一获得对应的正数再加上符号,不然是得到负数的表示 13 | else: 14 | res = res & 0xffffffff # 对于正数还要截断结果才对 15 | return res 16 | 17 | 18 | def test(method, random_samples=False): 19 | # test settings 20 | times = 10 21 | 22 | sol = method() 23 | data = 13, 5 24 | # data = -85, 107 25 | res = sol.Add(data[0], data[1]) 26 | print(res) 27 | 28 | if random_samples: 29 | import random 30 | for _ in range(times): 31 | data = random.randint(-100, 200), random.randint(-100, 200) 32 | print(data) 33 | res = sol.Add(data[0], data[1]) 34 | print(res) 35 | 36 | 37 | test(Solution, True) 38 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ48 最长不含重复数组的子字符串.py: -------------------------------------------------------------------------------- 1 | # 使用一个指针 prev 记录在这个指针之后就没有重复的部分, 2 | # 仅当有重复字符而且重复的在 prev 的部分时更新指针 3 | # 最后记录数组中最多不重复的部分返回 4 | class Solution: 5 | def lengthOfLongestSubstring(self, s: str) -> int: 6 | prev = -1 # set margin right could save a lot of trouble, think about its meaning 7 | ret = 0 8 | letters = dict() 9 | for i, letter in enumerate(s): 10 | if letter in letters and prev < letters[letter]: 11 | prev = letters[letter] 12 | letters[letter] = i 13 | 14 | ret = max(ret, i - prev) # update ret based on the prev 15 | 16 | return ret 17 | 18 | 19 | sol = Solution() 20 | print(sol.lengthOfLongestSubstring('abcdcab')) 21 | print(sol.lengthOfLongestSubstring('')) 22 | print(sol.lengthOfLongestSubstring("tmmzuxt")) 23 | print(sol.lengthOfLongestSubstring('abcdabcd')) 24 | print(sol.lengthOfLongestSubstring('abcdcabdab')) 25 | print(sol.lengthOfLongestSubstring("abfdshfkaksfbcakhsoaihabfeoifnanfslacnlanceoonczsccabcbb")) 26 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ5 用两个栈实现队列.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | def __init__(self): 4 | self.stack1 = [] 5 | self.stack2 = [] 6 | 7 | def push(self, node): 8 | self.stack1.append(node) 9 | 10 | def pop(self): 11 | if not self.stack2: 12 | while self.stack1: 13 | self.stack2.append(self.stack1.pop()) 14 | res = self.stack2.pop() 15 | return res 16 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ50 数组中重复的数字.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # 链接:https://www.nowcoder.com/questionTerminal/623a5ac0ea5b4e5f95552655361ae0a8?answerType=1&f=discussion 来源:牛客网 3 | # 方法二:in-place算法 4 | # 方法一中的一个条件我们没有用到。也就是数据的范围是0-n-1。所以我们可以这么做: 5 | # 6 | # 设置一个指针i指向开头0, 7 | # 8 | # 对于arr[i]进行判断,如果arr[i] == i, 说明下标为i的数据正确的放在了该位置上,让i++ 9 | # 10 | # 如果arr[i] != i, 说明没有正确放在位置上,那么我们就把arr[i]放在正确的位置上,也就是交换 11 | # arr[i] 和arr[arr[i]]。交换之后,如果arr[i] != i, 继续交换。 12 | # 13 | # 如果交换的过程中,arr[i] == arr[arr[i]],说明遇到了重复值,返回即可。 14 | 15 | class Solution: 16 | # 这里要特别注意~找到任意重复的一个值并赋值到duplication[0] 17 | # 函数返回True/False 18 | def duplicate(self, numbers, duplication): 19 | # write code here 20 | numset = set() 21 | for num in numbers: 22 | if num in numset: 23 | duplication[0] = num 24 | return True 25 | else: 26 | numset.add(num) 27 | return False -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ51 构建乘积数组.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | def multiply(self, A): 4 | if not A: 5 | return A 6 | mat1 = [A[0]] 7 | mat2 = [A[-1]] 8 | for i in range(1, len(A)): 9 | mat1.append(A[i] * mat1[-1]) 10 | mat2.insert(0, A[-1 - i] * mat2[0]) 11 | ret = [] 12 | for i in range(len(A)): 13 | if i - 1 < 0: 14 | ret.append(mat2[1]) 15 | elif i + 1 == len(A): 16 | ret.append(mat1[-2]) 17 | else: 18 | ret.append(mat1[i - 1] * mat2[i + 1]) # index 错误,除了本身索引越界,也可能是创造的list不够长 19 | return ret 20 | 21 | 22 | sol = Solution() 23 | print(sol.multiply([1, 2, 3, 4, 5, 6])) 24 | print(sol.multiply([6])) 25 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ52 正则表达式匹配.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | # s, pattern都是字符串 4 | def match(self, s, pattern): 5 | pass 6 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ54 字符流中第一个不重复的字符.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | def __init__(self): 4 | self.str = [] 5 | self.times = [] 6 | 7 | # 返回对应char 8 | def FirstAppearingOnce(self): 9 | try: 10 | idx = self.times.index(1) 11 | return self.str[idx] 12 | 13 | except ValueError: 14 | return '#' 15 | 16 | def Insert(self, char): 17 | if char in self.str: 18 | self.times[self.str.index(char)] += 1 19 | else: 20 | self.str.append(char) 21 | self.times.append(1) 22 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ55 链表中环的入口结点.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | 4 | class ListNode: 5 | def __init__(self, x): 6 | self.val = x 7 | self.next = None 8 | 9 | 10 | def stringToIntegerList(input): 11 | # print('input',input) 12 | return json.loads(input) 13 | 14 | # list 转换成链表 15 | def stringToListNode(input): 16 | # Generate list from the input 17 | # numbers = stringToIntegerList(input) 18 | numbers = input 19 | # print('numbers', numbers) 20 | 21 | # Now convert that list into linked list 22 | dummyRoot = ListNode(0) 23 | ptr = dummyRoot 24 | for number in numbers: 25 | ptr.next = ListNode(number) 26 | ptr = ptr.next 27 | 28 | ptr = dummyRoot.next 29 | return ptr 30 | 31 | class Solution: 32 | def EntryNodeOfLoop(self, pHead): 33 | slowvisit = set() 34 | if pHead: 35 | slow = pHead 36 | while slow: 37 | if slow in slowvisit: 38 | return slow 39 | slowvisit.add(slow) 40 | slow = slow.next 41 | return 42 | else: 43 | return 44 | 45 | head = stringToListNode([1,0]) 46 | sol = Solution() 47 | res = sol.EntryNodeOfLoop(head) 48 | print(res) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ56 删除链表中重复的结点.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class ListNode: 3 | def __init__(self, x): 4 | self.val = x 5 | self.next = None 6 | 7 | 8 | class Solution: 9 | def deleteDuplication(self, pHead): 10 | if not pHead or not pHead.next: 11 | return pHead 12 | else: 13 | node = pHead 14 | Dummyhead = ListNode(0) 15 | prev = Dummyhead 16 | 17 | while node and node.next: 18 | if node.val == node.next.val: 19 | before = node.next 20 | node = node.next.next 21 | 22 | else: 23 | prev.next = node 24 | prev = node 25 | before = node 26 | node = node.next 27 | 28 | if not node or before.val != node.val: 29 | prev.next = node 30 | 31 | return Dummyhead.next -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ59 之字形打印二叉树.py: -------------------------------------------------------------------------------- 1 | # BFS with tag, 每次得到结果之后反向~ 2 | class Solution: 3 | def Print(self, root): 4 | res = [] 5 | 6 | def BFSwithTag(Q): 7 | while Q: 8 | (node, level) = Q.pop(0) 9 | if level > len(res) - 1: 10 | res.append([node.val]) 11 | if level % 2 == 0 and level > 0: 12 | res[-2].reverse() 13 | else: 14 | res[level].append(node.val) 15 | if node.left is not None: 16 | Q.append((node.left, level + 1)) 17 | if node.right is not None: 18 | Q.append((node.right, level + 1)) 19 | if level % 2 == 1: 20 | res[-1].reverse() 21 | 22 | if root is not None: 23 | queue = [(root, 0)] 24 | BFSwithTag(queue) 25 | 26 | return res 27 | 28 | from Debug_BST import list2Tree, PrintTree 29 | 30 | sol = Solution() 31 | data = [8, 6, 10, 5, 7, 9, 11,1,2,1,3,1,4,1,5,2,3,1,3] 32 | 33 | tree = list2Tree(data) 34 | printT = PrintTree() 35 | printT.printTree(tree) 36 | 37 | res = sol.zigzagLevelOrder(tree) 38 | print(res) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ6 旋转数组的最小数字.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | 3 | # 懒方法看题目为什么不对 4 | class Solution1: 5 | def minNumberInRotateArray(self, rotateArray): 6 | if not rotateArray: 7 | return 0 8 | ret = rotateArray[0] 9 | for num in rotateArray: 10 | ret = min(ret, num) 11 | return ret 12 | 13 | 14 | # 二分查找中间的最小值 15 | class Solution: 16 | def minNumberInRotateArray(self, rotateArray): 17 | if not rotateArray: 18 | return 0 19 | low, high = 0, len(rotateArray) - 1 20 | mid = (high + low) // 2 21 | ret = rotateArray[0] 22 | while low < high: 23 | if rotateArray[low] < rotateArray[high]: 24 | return rotateArray[low] 25 | if rotateArray[mid] > rotateArray[high]: 26 | low = mid + 1 27 | elif rotateArray[mid] > rotateArray[high]: 28 | high = mid 29 | else: 30 | high -= 1 31 | ret = min(ret, rotateArray[mid]) 32 | 33 | mid = (high + low) // 2 34 | return ret 35 | 36 | 37 | sol = Solution() 38 | print(sol.minNumberInRotateArray([4, 5, 6, 3, 4])) 39 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ60 把二叉树打印成多行.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | # queue with Tag 8 | class Solution: 9 | # 返回二维列表[[1,2],[4,5]] 10 | def Print(self, pRoot): 11 | if not pRoot: 12 | return [] 13 | else: 14 | ret = [] 15 | queue = [(pRoot, 0)] 16 | while queue: 17 | node, level = queue.pop(0) 18 | if len(ret) list: 4 | dp = [0 for i in range(6 * n)] 5 | dp[0:6] = [1 / 6, 1 / 6, 1 / 6, 1 / 6, 1 / 6, 1 / 6] 6 | 7 | for i in range(2, n + 1): 8 | for num in range(6 * i - 1, i - 2, -1): # 同时需要更新的值是到i的前一位 9 | dp[num] = sum([dp[num - j] / 6 for j in range(1, 7) if num - j >= i - 2]) # 注意边界,不是数组的边界而是可以达到的最小 10 | 11 | return dp[n - 1:6 * n] 12 | 13 | 14 | # [0, 0, 1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0, 0] 15 | # [0, 0, 0, 1, 3, 6, 10, 15, 21, 25, 27, 27, 25, 21, 15, 10, 6, 3, 1] 16 | 17 | sol = Solution() 18 | print(sol.twoSum(3)) 19 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ63 二叉搜索树的第k个结点.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # class TreeNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | # 中序遍历到第k个结点返回 8 | class Solution: 9 | # 返回对应节点TreeNode 10 | def KthNode(self, pRoot, k): 11 | 12 | def helper(node): 13 | if not node: 14 | return 15 | helper(node.left) 16 | curr_idx = 0 17 | global curr_idx 18 | curr_idx += 1 19 | if curr_idx == k: 20 | return node.val 21 | helper(node.right) 22 | 23 | if pRoot and k > 0: 24 | return helper(pRoot) 25 | else: 26 | return 27 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ63 数据流中的中位数.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | import heapq 3 | 4 | 5 | class Solution: 6 | def __init__(self): 7 | self.large, self.small = [], [] 8 | 9 | def Insert(self, num): 10 | if len(self.large) == len(self.small): 11 | heapq.heappush(self.large, -heapq.heappushpop(self.small, -num)) 12 | else: 13 | heapq.heappush(self.small, -heapq.heappushpop(self.large, num)) 14 | # print(self.large, self.small) 15 | 16 | def GetMedian(self): 17 | if len(self.small) == len(self.large): 18 | return (self.large[0] - self.small[0]) / 2.0 19 | else: 20 | return float(self.large[0]) 21 | 22 | 23 | # 5.00 3.50 3.00 3.50 3.00 3.50 4.00 3.50 4.00 24 | 25 | 26 | sol = Solution() 27 | sol.Insert(5) 28 | print(sol.GetMedian()) 29 | sol.Insert(2) 30 | print(sol.GetMedian()) 31 | sol.Insert(3) 32 | print(sol.GetMedian()) 33 | sol.Insert(4) 34 | print(sol.GetMedian()) 35 | sol.Insert(1) 36 | print(sol.GetMedian()) 37 | sol.Insert(6) 38 | print(sol.GetMedian()) 39 | sol.Insert(7) 40 | print(sol.GetMedian()) 41 | sol.Insert(0) 42 | print(sol.GetMedian()) 43 | sol.Insert(8) 44 | print(sol.GetMedian()) 45 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ64 滑动窗口中的最大值.py: -------------------------------------------------------------------------------- 1 | 2 | # 可以用单调栈,找到邻近更大的,如果有效则加入比较,如果没有,则自己为最大,这样为 O(n) 3 | # -*- coding:utf-8 -*- 4 | class Solution: 5 | def maxInWindows(self, num, size): 6 | res = [] 7 | if size == 0: 8 | return res 9 | for idx in range(len(num) - size + 1): 10 | sample = num[idx:idx + size] 11 | res.append(max(sample)) 12 | return res 13 | 14 | 15 | sol = Solution() 16 | res = sol.maxInWindows([2, 3, 4, 2, 6, 2, 5, 1], 3) 17 | print(res) 18 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ67 剪绳子.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | class Solution: 3 | def cutRope(self, number): 4 | memoi = {2: 1, 3: 2} 5 | 6 | def helper(number): 7 | result = number 8 | if number in memoi: 9 | return max(result, memoi[number]) 10 | 11 | for i in range(2, number - 1): 12 | result = max(result, helper(number - i) * i) 13 | 14 | memoi[number] = result 15 | 16 | return result 17 | 18 | res = number - 1 19 | for i in range(2, number - 1): 20 | res = max(res, helper(number - i) * i) 21 | return res 22 | 23 | 24 | def test(method, random_samples=False): 25 | # test settings 26 | times = 10 27 | 28 | sol = method() 29 | data = 8 30 | res = sol.cutRope(data) 31 | print(res) 32 | 33 | if random_samples: 34 | import random 35 | for _ in range(times): 36 | data = random.randint(2, 20) 37 | print(data) 38 | res = sol.cutRope(data) 39 | print(res) 40 | 41 | 42 | test(Solution, True) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ7 斐波那契数列.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # 仅仅利用前面两个数,因此迭代地求就可以 3 | class Solution: 4 | def Fibonacci(self, n): 5 | if n == 1: 6 | return 1 7 | elif n == 0: 8 | return 0 9 | else: 10 | a, b = 0, 1 11 | for i in range(2, n + 1): # 循环要到n+1,不然走不到n!!! 12 | res = a + b 13 | a, b = b, res 14 | return res 15 | 16 | 17 | sol = Solution() 18 | print(sol.Fibonacci(2)) 19 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ8 跳台阶.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def jumpFloor(self, number): 3 | if number <= 0: 4 | return 0 5 | elif number < 3: 6 | return number 7 | else: 8 | a = 1 9 | b = 2 10 | for i in range(3, number+1): 11 | res = a + b 12 | a, b = b, res 13 | # print(res,a,b) 14 | 15 | return res 16 | 17 | 18 | sol = Solution() 19 | print(sol.jumpFloor(4)) 20 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/JZ9 变态跳台阶.py: -------------------------------------------------------------------------------- 1 | # -*- coding:utf-8 -*- 2 | # 链接:https://www.nowcoder.com/questionTerminal/22243d016f6b47f2a6928b4313c85387?answerType=1&f=discussion 3 | # 来源:牛客网 4 | # 5 | # 方法二:继续优化 空间复杂度O(1)时间复杂度O(N) 6 | # 对于方法一中的:f[n] = f[n-1] + f[n-2] + ... + f[0] 7 | # 8 | # 那么f[n-1] 为多少呢? 9 | # 10 | # f[n-1] = f[n-2] + f[n-3] + ... + f[0] 11 | # 12 | # 所以一合并,f[n] = 2*f[n-1],初始条件f[0] = f[1] = 1 13 | # 14 | # 所以可以采用递归,记忆化递归,动态规划,递推。具体详细过程,可查看青蛙跳台阶。 15 | # 16 | # 这里直接贴出递推的代码。 17 | 18 | class Solution: 19 | def __init__(self): 20 | self.memoi = {1: 1, 2: 2} 21 | 22 | def jumpFloorII(self, number): 23 | if number < 1: 24 | return 0 25 | elif number in self.memoi: 26 | return self.memoi[number] 27 | else: 28 | res = 0 29 | for i in range(1, number): 30 | res += self.jumpFloorII(number - i) 31 | res += 1 # 一次跳n阶台阶 32 | self.memoi[number] = res 33 | return res 34 | 35 | 36 | sol = Solution() 37 | print(sol.jumpFloorII(3)) 38 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L102. Binary Tree Level Order Traversal.py: -------------------------------------------------------------------------------- 1 | from .Debug_BST import TreeNode, PrintTree, list2Tree 2 | 3 | 4 | # BFS with tag 5 | class Solution: 6 | def levelOrder(self, root: TreeNode): 7 | self.res = [] 8 | 9 | def BFSwithTag(Q): 10 | while Q: 11 | (node, level) = Q.pop(0) 12 | if level > len(self.res) - 1: 13 | self.res.append([node.val]) 14 | else: 15 | self.res[level].append(node.val) 16 | if node.left is not None: 17 | Q.append((node.left, level + 1)) 18 | if node.right is not None: 19 | Q.append((node.right, level + 1)) 20 | 21 | if root is not None: 22 | queue = [(root, 0)] 23 | BFSwithTag(queue) 24 | return self.res 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L104. Maximum Depth of Binary Tree.py: -------------------------------------------------------------------------------- 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 | 9 | class Solution: 10 | def maxDepth(self, root: TreeNode) -> int: 11 | if not root: 12 | return 0 13 | 14 | return max(self.maxDepth(root.left), self.maxDepth(root.right))+1 15 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L10_RegularMatching.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | class Solution: 5 | def isMatch(self, s, p): 6 | if s == p: 7 | return True 8 | PLen, SLen = len(p), len(s) 9 | countStar = len(re.findall("\*", p)) 10 | if not (PLen == SLen) and (not ("*" in p) or not PLen - 2 * countStar <= SLen): 11 | return False 12 | else: 13 | equal = (s[0] == p[0]) or (p[0] == ".") 14 | if not equal and p[1] != "*": 15 | return False 16 | elif not equal and p[1] == "*": 17 | return self.isMatch(s[1:], p[2:]) 18 | elif equal and p[0:2] == ".*": 19 | return self.isMatch(s[1:], p[1:]) 20 | 21 | 22 | sol = Solution() 23 | s = "mississippi" 24 | p = "mis*is*p*." 25 | print(sol.isMatch(s, p)) 26 | s = "aab" 27 | p = "c*a*b" 28 | print(sol.isMatch(s, p)) 29 | print(sol.isMatch(s, p)) 30 | print(sol.isMatch(s, p)) 31 | print(sol.isMatch(s, p)) 32 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L110. Balanced Binary Tree.py: -------------------------------------------------------------------------------- 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 | 9 | # 后序遍历,并统计深度,如果左右深度只差大于1 则不是平衡二叉树 10 | class Solution: 11 | def isBalanced(self, root: TreeNode) -> bool: 12 | 13 | def traverse(node): 14 | if not node: 15 | return 0 16 | leftdepth = traverse(node.left) 17 | rightdepth = traverse(node.right) 18 | if abs(leftdepth - rightdepth) > 1 or leftdepth == -1 or rightdepth == -1: 19 | return -1 20 | 21 | return max(leftdepth, rightdepth) + 1 22 | 23 | return [True, False][traverse(root) == -1] 24 | 25 | 26 | from Debug_BST import list2Tree, PrintTree 27 | 28 | sol = Solution() 29 | data = [8, 1, 10, 5, None, None, 11] 30 | data = [8, 10, 1, 1, None, None, 8, None, 19] 31 | data = [1, 2, 2, 3, 3, None, None, 4, 4] 32 | 33 | tree = list2Tree(data) 34 | printT = PrintTree() 35 | printT.printTree(tree) 36 | 37 | res = sol.isBalanced(tree) 38 | print(res) 39 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L111. Minimum Depth of Binary Tree.py: -------------------------------------------------------------------------------- 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 | 9 | class Solution: 10 | def minDepth(self, root: TreeNode) -> int: 11 | if not root: 12 | return 0 13 | else: 14 | queue = [(root, 1)] 15 | while queue: 16 | node, level = queue.pop(0) 17 | children = (node.left, node.right) 18 | if not any(children): 19 | return level 20 | 21 | for nei in children: 22 | if nei: 23 | queue.append((nei, level + 1)) 24 | 25 | 26 | from Debug_BST import list2Tree, PrintTree 27 | 28 | sol = Solution() 29 | data = [''] 30 | 31 | tree = list2Tree(data) 32 | printT = PrintTree() 33 | printT.printTree(tree) 34 | 35 | res = sol.minDepth(tree) 36 | print(res) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L1143 Longest Common Subsequence.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | class Solution: 5 | def longestCommonSubsequence(self, text1: str, text2: str) -> int: 6 | if text2 is '' or text1 is '': 7 | return 0 8 | LCS = np.zeros((len(text1) + 1, len(text2) + 1)) 9 | for i in range(1, len(text1) + 1): 10 | for j in range(1, len(text2) + 1): 11 | if text1[i - 1] == text2[j - 1]: 12 | LCS[i, j] = LCS[i - 1, j - 1] + 1 13 | else: 14 | LCS[i, j] = max(LCS[i - 1, j], LCS[i, j - 1]) 15 | 16 | return int(LCS[len(text1), len(text2)]) 17 | 18 | 19 | # test 20 | import random 21 | import string 22 | 23 | # test settings 24 | times = 100 25 | 26 | sol = Solution() 27 | 28 | for _ in range(times): 29 | len1, len2 = random.randint(0, 10), random.randint(1, 10) 30 | str1 = ''.join(random.sample(string.ascii_lowercase, len1)) 31 | str2 = ''.join(random.sample(string.ascii_lowercase, len2)) 32 | print(str1, str2, end=' ') 33 | res = sol.longestCommonSubsequence(str1, str2) 34 | print(' and their LCS is ', res) 35 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L1146. Snapshot Array.py: -------------------------------------------------------------------------------- 1 | # 在 get 部分还是操作太多了,使用哈希表来记录已有操作节省空间, 同时保存了记录,不用反复寻找 2 | from collections import defaultdict 3 | 4 | 5 | class SnapshotArray: 6 | def __init__(self, length: int): 7 | self.data = defaultdict(dict) 8 | self.sid = -1 9 | self.length = length 10 | 11 | def set(self, index: int, val: int) -> None: 12 | self.data[self.sid+1][index] = val 13 | print(self.data) 14 | 15 | def snap(self) -> int: 16 | self.sid += 1 17 | self.data[self.sid] = self.data[self.sid - 1].copy() 18 | return self.sid 19 | 20 | def get(self, index: int, snap_id: int) -> int: 21 | res = self.data[snap_id].get(index, 0) 22 | 23 | return res 24 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L121_BestTimeB%S.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices): 3 | if prices == [] or len(prices) == 1: 4 | return 0 5 | diff = [] 6 | for i in range(1,len(prices)): 7 | diff.append((prices[i]-prices[i-1])) 8 | print(diff) 9 | for i in range(len(diff)-1,0,-1): 10 | if diff[i]>0: 11 | diff[i-1] += diff[i] 12 | return max(max(diff),0) 13 | sol = Solution() 14 | # res = sol.maxProfit([7,1,5,3,6,4]) 15 | # print(res) 16 | res = sol.maxProfit([7,6,4,3,1]) 17 | print(res) 18 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L122. Best Time to Buy and Sell Stock II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: list) -> int: 3 | ret = 0 4 | for i in range(len(prices) - 1): 5 | ret = [ret, ret + prices[i + 1] - prices[i]][prices[i + 1] - prices[i] > 0] 6 | return ret 7 | 8 | 9 | sol = Solution() 10 | print(sol.maxProfit([7, 1, 5, 3, 6, 4])) 11 | print(sol.maxProfit([7, 6, 5, 4, 3, 2])) 12 | print(sol.maxProfit([1, 2, 3, 4, 5, 6])) 13 | print(sol.maxProfit([1, 3, 2, 6, 2, 4])) 14 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L12_IntegertoRoman.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | """seperate and combine 3 | could use a more refined scale: 1 4 5 9 etc 4 | which means bigger and substract""" 5 | def intToRoman(self, num): 6 | numList = [1,4,5,9,10,40,50,90,100,400,500,900,1000] 7 | numRomanDict = {1:'I', 4:'IV', 5:'V', 9:'IX', 10:'X', 40:'XL', 8 | 50:'L', 90:'XC', 100:'C', 400:'CD', 500:'D', 9 | 900:'CM', 1000:'M'} 10 | sepnum = [] 11 | res = '' 12 | for i in range(len(str(num))-1,-1,-1): 13 | sep = (num//(10**i))%10 14 | sepnum.append(sep) 15 | if sep == 1 or sep == 4 or sep == 5 or sep == 9: 16 | res += numRomanDict[sep*(10**i)] 17 | elif sep < 4: 18 | res += numRomanDict[(10**i)]*sep 19 | elif sep>5: 20 | res += numRomanDict[5*(10**i)] + numRomanDict[(10**i)]*(sep-5) 21 | 22 | print(sepnum) 23 | return res 24 | 25 | sol = Solution() 26 | res = sol.intToRoman(1994) 27 | print(res) 28 | 29 | 30 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L136. Single Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def singleNumber(self, nums): 3 | for num in nums[1:]: 4 | nums[0] = nums[0]^num 5 | return nums[0] 6 | 7 | sol = Solution() 8 | print(sol.singleNumber([1,2,1,2,3,4,5,4,3])) 9 | print(sol.singleNumber([1,-2,1,-2,0,4,5,4,0])) 10 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L137. Single Number II.py: -------------------------------------------------------------------------------- 1 | # class Solution: 2 | # def singleNumber(self, nums): 3 | # a,b = 0,0 4 | # for val in nums: 5 | # b = (b ^ val) & ~a 6 | # a = (a ^ val) & ~b 7 | # print('a,b',a,b) 8 | # return b 9 | 10 | class Solution: 11 | def singleNumber(self, nums): 12 | a,b = 0,0 13 | for c in nums: 14 | a_current = a&~b&~c | ~a&b&c 15 | b= ~a&b&~c|~a&~b&c 16 | a = a_current 17 | print(a|b,b) 18 | return b 19 | 20 | sol =Solution() 21 | # print(sol.singleNumber([1,3,1,2,1,2,2,3,4,3])) 22 | # print(sol.singleNumber([1,3,2,4,5,3])) 23 | print(sol.singleNumber([0,1,0,1,0,1,99,10,99])) 24 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L1376. Time Needed to Inform All Employees.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | 4 | class Solution: 5 | def numOfMinutes(self, n: int, headID: int, manager: list, informTime: list) -> int: 6 | head2child = defaultdict(list) 7 | for idx, leader in enumerate(manager): 8 | head2child[leader].append(idx) 9 | 10 | def helper(leaderID): 11 | res = 0 12 | if leaderID not in head2child: 13 | return 0 14 | 15 | for ele in head2child[leaderID]: # dfs 先左子再右子,不断向下,并取最大,不需要存储 16 | childres = helper(ele) + informTime[leaderID] 17 | res = max(res, childres) 18 | return res 19 | 20 | return helper(headID) 21 | 22 | 23 | sol = Solution() 24 | data = 7, 6, [1, 2, 3, 4, 5, 6, -1], [0, 6, 5, 4, 3, 2, 1] 25 | data = 15, 0, [-1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6], [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0] 26 | data = 4, 2, [3, 3, -1, 2], [0, 0, 162, 914] 27 | data = 6, 2, [2, 2, -1, 2, 2, 2], [0, 0, 1, 0, 0, 0] 28 | data = 1, 0, [-1], [0] 29 | rs = sol.numOfMinutes(data[0], data[1], data[2], data[3]) 30 | print(rs) 31 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L142. Linked List Cycle II.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | class ListNode: 3 | def __init__(self, x): 4 | self.val = x 5 | self.next = None 6 | 7 | # tail connects to node index 0 8 | class Solution: 9 | def detectCycle(self, head: ListNode) -> ListNode: 10 | if not head: 11 | return None 12 | else: 13 | nodeset = set() 14 | while head: 15 | if head in nodeset: 16 | return head 17 | else: 18 | nodeset.add(head) 19 | head = head.next 20 | 21 | return None 22 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L143. Reorder List.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | class ListNode: 3 | def __init__(self, val=0, next=None): 4 | self.val = val 5 | self.next = next 6 | 7 | # 1. 全部装入栈中,依次取首尾元素就可 8 | # 2. 将链表从中间分成两个链表,倒序后面的链表,依次按奇偶插入链表 9 | class Solution: 10 | def reorderList(self, head: ListNode) -> None: 11 | """ 12 | Do not return anything, modify head in-place instead. 13 | """ 14 | if not head: 15 | return head 16 | deque = [] 17 | pointer = head 18 | while pointer: 19 | deque.append(pointer) 20 | pointer = pointer.next 21 | 22 | p = deque.pop(0) 23 | while deque: 24 | p.next = deque.pop(-1) 25 | p = p.next 26 | 27 | if deque: 28 | p.next = deque.pop(0) 29 | p = p.next 30 | 31 | p.next = None 32 | prettyPrintLinkedList(head) 33 | 34 | 35 | from L61_Rotate_List_linked_list_debug import stringToListNode, prettyPrintLinkedList 36 | 37 | sol = Solution() 38 | 39 | head = stringToListNode([0, 1, 2, 3, 4, 5, 6]) 40 | head = stringToListNode([]) 41 | prettyPrintLinkedList(head) 42 | prettyPrintLinkedList(sol.reorderList(head)) 43 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L1466. Reorder Routes to Make All Paths Lead to the City Zero.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minReorder(self, n: int, connections) -> int: 3 | reachableset = {0} 4 | cnt = 0 5 | while len(reachableset) < n: 6 | for ele in connections: 7 | if ele[1] in reachableset: 8 | reachableset.add(ele[0]) 9 | elif ele[0] in reachableset: 10 | reachableset.add(ele[1]) 11 | cnt += 1 12 | 13 | return cnt 14 | 15 | 16 | sol = Solution() 17 | print(sol.minReorder(n=6, connections=[[0, 1], [1, 3], [2, 3], [4, 0], [4, 5]])) 18 | print(sol.minReorder(n=5, connections=[[1, 0], [1, 2], [3, 2], [3, 4]])) 19 | print(sol.minReorder(n=3, connections=[[1, 0], [2, 0]])) 20 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L1470. Shuffle the Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def shuffle(self, nums: list, n: int) -> list: 3 | def helper(idx): 4 | if idx < n: 5 | return 2 * idx 6 | else: 7 | return 2 * (idx - n) + 1 8 | 9 | for i in range(len(nums)): 10 | if nums[i] < 0 or i == 0: 11 | continue 12 | gotoidx = helper(i) 13 | nextnum = -nums[i] 14 | while nums[gotoidx] > 0: 15 | # print(nums, nextnum, gotoidx) 16 | nextnum, nums[gotoidx] = -nums[gotoidx], nextnum 17 | gotoidx = helper(gotoidx) 18 | for i in range(1, len(nums)): 19 | nums[i] = -nums[i] 20 | 21 | return nums 22 | 23 | 24 | sol = Solution() 25 | print(sol.shuffle([2, 5, 1, 3, 4, 7], 3)) 26 | print(sol.shuffle([1,2,3,4,4,3,2,1], 4)) 27 | print(sol.shuffle([1,1,2,2], 2)) 28 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L1471. The k Strongest Values in an Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getStrongest(self, arr: list, k: int) -> list: 3 | if k == len(arr): 4 | return arr 5 | arr.sort() 6 | median = arr[(len(arr) - 1) // 2] 7 | ret = [] 8 | head, tail = 0, len(arr) - 1 9 | while len(ret) < k: 10 | abshead = abs(arr[head] - median) 11 | abstail = abs(arr[tail] - median) 12 | print(arr,median, head, tail, abshead, abstail, ret) 13 | if abstail >= abshead: 14 | ret.append(arr[tail]) 15 | tail -= 1 16 | else: 17 | ret.append(arr[head]) 18 | head += 1 19 | return ret 20 | 21 | 22 | sol = Solution() 23 | # print(sol.getStrongest(arr=[1, 2, 3, 4, 5], k=2)) 24 | # print(sol.getStrongest(arr=[1, 1, 3, 5, 5], k=2)) 25 | print(sol.getStrongest(arr=[6, 7, 11, 7, 6, 8], k=5)) 26 | # print(sol.getStrongest([6, -3, 7, 2, 11], k=3)) 27 | print(sol.getStrongest(arr=[-7, 22, 17, 3], k=2)) 28 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L148. sort linked list.py: -------------------------------------------------------------------------------- 1 | 2 | class ListNode: 3 | def __init__(self, val=0, next=None): 4 | self.val = val 5 | self.next = next 6 | 7 | # sort the list use merge sort, remember to use some count when split 8 | class Solution: 9 | def sortList(self, head: ListNode) -> ListNode: 10 | pass 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L149. Max Points on a Line0811.py: -------------------------------------------------------------------------------- 1 | 2 | # hough 变换检测 3 | class Solution: 4 | def maxPoints(self, points: List[List[int]]) -> int: 5 | pass -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L14_LongestCommonPrefix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestCommonPrefix(self, strs): 3 | common = '' 4 | if strs == [] or strs == [""]: 5 | return common 6 | cnt = min(len(str) for str in strs) 7 | for i in range(cnt): 8 | c = strs[0][i] 9 | for str in strs: 10 | if str[i] != c: 11 | return common 12 | common += c 13 | return common 14 | 15 | sol = Solution() 16 | # res = sol.longestCommonPrefix(["dog","racecar","car"]) 17 | # res = sol.longestCommonPrefix(["flower","flow","flight"]) 18 | # res = sol.longestCommonPrefix(['fdsf','fdsd','fdsrwdf']) 19 | res = sol.longestCommonPrefix(['a']) 20 | 21 | print(res) 22 | 23 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L15. 3Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def threeSum(self, nums): 3 | nums.sort() 4 | ret = [] 5 | for i in range(len(nums) - 1): 6 | first = nums[i] 7 | if i - 1 >= 0 and first == nums[i - 1]: 8 | continue 9 | target = 0 - first 10 | pt1, pt2 = i + 1, len(nums) - 1 11 | while pt1 < pt2: 12 | remain = target - nums[pt1] 13 | if remain > nums[pt2]: 14 | pt1 += 1 15 | elif remain == nums[pt2]: 16 | second = nums[pt1] 17 | ret.append([first, second, remain]) 18 | pt1 += 1 19 | pt2 -= 1 20 | while pt1 < pt2 and nums[pt1] == second: 21 | pt1 += 1 22 | while pt1 < pt2 and nums[pt2] == remain: 23 | pt2 -= 1 24 | else: 25 | pt2 -= 1 26 | return ret 27 | 28 | 29 | sol = Solution() 30 | print(sol.threeSum([0, 0, 0, 0, 0, 0, 0, 0])) 31 | print(sol.threeSum([0, 0])) 32 | print(sol.threeSum([1, -1, 1])) 33 | print(sol.threeSum([1, -1, 0, -1, 0, 1])) 34 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L150. Evaluate Reverse Polish Notation.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def evalRPN(self, tokens) -> int: 3 | operator = ['+', '-', '*', '/'] 4 | data = [] 5 | for token in tokens: 6 | if token in operator: 7 | # print(data) 8 | x2, x1 = data.pop(-1), data.pop(-1) 9 | res = int(eval(x1 + token + x2)) 10 | # print(res) 11 | data.append(str(res)) 12 | else: 13 | data.append(token) 14 | return int(data[0]) 15 | 16 | 17 | sol = Solution() 18 | print(sol.evalRPN(["2", "1", "+", "3", "*"])) 19 | print(sol.evalRPN(["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"])) 20 | print(sol.evalRPN([])) 21 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L155_minStack.py: -------------------------------------------------------------------------------- 1 | class singleLinkedNode: 2 | def __init__(self, x): 3 | self.data = x 4 | self.next = None 5 | 6 | 7 | class MinStack: 8 | 9 | def __init__(self): 10 | """ 11 | initialize your data structure here. 12 | """ 13 | self.head = None 14 | self.datalist = [] 15 | 16 | def push(self, x): 17 | """ 18 | :type x: int 19 | :rtype: void 20 | """ 21 | node = singleLinkedNode(x) 22 | node.next = self.head 23 | self.head = node 24 | self.datalist.append(x) 25 | 26 | def pop(self): 27 | """ 28 | :rtype: void 29 | """ 30 | self.datalist.remove(self.head.data) 31 | self.head = self.head.next 32 | 33 | def top(self): 34 | """ 35 | :rtype: int 36 | """ 37 | return self.head.data 38 | 39 | def getMin(self): 40 | """ 41 | :rtype: int 42 | """ 43 | return min(self.datalist) 44 | 45 | 46 | def test(): 47 | minStack = MinStack() 48 | minStack.push(-2) 49 | minStack.push(0) 50 | minStack.push(-3) 51 | minStack.getMin() 52 | minStack.pop() 53 | minStack.top() 54 | minStack.getMin() 55 | 56 | test() -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L155_othermethod.py: -------------------------------------------------------------------------------- 1 | # 使用列表来构建栈,其中在添加元素时同时添加元素和当前最小值 2 | # (因为只允许从一端移动,所以最小值不会随顶端元素变动而变动) 3 | # 栈的顺序就是列表中元素的顺序,添加和删除元素就是列表的append和pop 4 | # 访问列表就可以得到第一个栈首元素值和最小值 5 | 6 | 7 | 8 | 9 | class MinStack: 10 | 11 | def __init__(self): 12 | self.q = [] 13 | 14 | # @param x, an integer 15 | # @return an integer 16 | def push(self, x): 17 | curMin = self.getMin() 18 | if curMin == None or x < curMin: 19 | curMin = x 20 | self.q.append((x, curMin)); 21 | 22 | # @return nothing 23 | def pop(self): 24 | self.q.pop() 25 | 26 | 27 | # @return an integer 28 | def top(self): 29 | if len(self.q) == 0: 30 | return None 31 | else: 32 | return self.q[len(self.q) - 1][0] 33 | 34 | 35 | # @return an integer 36 | def getMin(self): 37 | if len(self.q) == 0: 38 | return None 39 | else: 40 | return self.q[len(self.q) - 1][1] 41 | 42 | def test(): 43 | minStack = MinStack() 44 | minStack.push(-2) 45 | minStack.push(0) 46 | minStack.push(-3) 47 | minStack.getMin() 48 | minStack.pop() 49 | minStack.top() 50 | minStack.getMin() 51 | 52 | test() -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L160. Intersection of Two Linked Lists.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | class ListNode: 3 | def __init__(self, x): 4 | self.val = x 5 | self.next = None 6 | 7 | 8 | # 走一遍,找到差,抛弃差,然后一一对比 9 | class Solution: 10 | def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: 11 | nodeA, nodeB = headA, headB 12 | 13 | while nodeA and nodeB: 14 | nodeA = nodeA.next 15 | nodeB = nodeB.next 16 | 17 | AStart = headA 18 | BStart = headB 19 | if nodeA: 20 | while nodeA: 21 | AStart = AStart.next 22 | nodeA = nodeA.next 23 | 24 | if nodeB: 25 | while nodeB: 26 | BStart = BStart.next 27 | nodeB = nodeB.next 28 | 29 | while AStart: 30 | if AStart == BStart: 31 | return AStart 32 | else: 33 | AStart = AStart.next 34 | BStart = BStart.next 35 | 36 | return None 37 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L167. Two Sum II - Input array is sorted.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums: List[int], target: int) -> List[int]: 3 | start,end = 0,len(nums)-1 4 | while nums[start]+nums[end] != target: 5 | if nums[start]+nums[end]>target: 6 | end -= 1 7 | else: 8 | start += 1 9 | return [start+1,end+1] -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L16_3SumClosest.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | """keep one still and adjust the rest""" 3 | def threeSumClosest(self, nums, target): 4 | nums.sort() 5 | result = nums[-1]+nums[-2]+nums[-3] 6 | for i in range(len(nums)-2): 7 | j,k = i+1,len(nums)-1 8 | while jtarget: 13 | k -= 1 14 | else: 15 | j += 1 16 | if abs(numSum-target)>1 8 | return cont 9 | 10 | sol = Solution() 11 | print(sol.hammingWeight(0b1111000101010)) 12 | print(sol.hammingWeight(0b11111111111111111111111111111101)) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L1_TwoSum.py: -------------------------------------------------------------------------------- 1 | # class Solution: 2 | # def twoSum(self, nums, target): 3 | # for i in range(len(nums)): 4 | # for j in range(i + 1, len(nums)): 5 | # if nums[i] + nums[j] == target: 6 | # return [i, j] 7 | 8 | # O(N) O(N) 利用字典找另外一个数 9 | class Solution: # infor: only two nums add together 10 | def twoSum(self, nums, target): 11 | num2indices = {} 12 | 13 | for k, num in enumerate(nums): 14 | remain = target - num 15 | if remain in num2indices and num2indices[remain] != k: 16 | return [k, num2indices[remain]] 17 | 18 | num2indices[num] = k 19 | 20 | return [] 21 | 22 | 23 | # 排序+ 双指针,O(N), O(1) 24 | 25 | 26 | sol = Solution() 27 | res = sol.twoSum(nums=[2, 3, 7, 8, 11, 15], target=15) 28 | res = sol.twoSum(nums=[2, 3, 1, 8, 11, 15], target=15) 29 | res = sol.twoSum(nums=[0, 4, 3], target=0) 30 | print(res) 31 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L201. Bitwise AND of Numbers Range.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def rangeBitwiseAnd(self, m, n): 3 | if n-m >= 1: 4 | res = '0' 5 | else: 6 | return m 7 | 8 | k = 1 9 | while 2**k <=n : 10 | print('k = ',k, 2**k,res) 11 | if 2**k-1 >=m: 12 | res += '0' 13 | else: 14 | res += '1' 15 | k+=1 16 | res = res[::-1] 17 | if res == '': 18 | return 0 19 | return int(res,2) 20 | 21 | so = Solution() 22 | print(so.rangeBitwiseAnd(5,7)) 23 | # print(so.rangeBitwiseAnd(0,2147483647)) 24 | # print(so.rangeBitwiseAnd(1,1)) 25 | # print(so.rangeBitwiseAnd(1,2)) 26 | 27 | # print(so.rangeBitwiseAnd(0,0)) 28 | # for i in range(100): 29 | # for j in range(i+1,100): 30 | # print(so.rangeBitwiseAnd(i,j)) 31 | 32 | 33 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L209. Minimum Size Subarray Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minSubArrayLen(self, s, nums): 3 | if nums == [] or s> sum(nums): 4 | return 0 5 | start,numSum,cnt,minLen = 0,0,0,len(nums)+1 6 | for num in nums: 7 | numSum += num 8 | cnt += 1 9 | while numSum-nums[start]>=s: 10 | numSum -= nums[start] 11 | start += 1 12 | cnt -= 1 13 | 14 | if numSum >= s: 15 | minLen = min(cnt,minLen) 16 | 17 | return minLen 18 | 19 | sol = Solution() 20 | print(sol.minSubArrayLen(7,[2,3,1,2,4,3])) 21 | print(sol.minSubArrayLen(7,[2,4,6,7,2,7,21,5,7,8,3,1,2,4,3])) 22 | print(sol.minSubArrayLen(7,[2,3,1])) 23 | print(sol.minSubArrayLen(7,[2,3,1,2,4,3])) 24 | 25 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L214_Shortest Palindrome.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/04_Algorithms/Leetcode/L214_Shortest Palindrome.py -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L215. KthLargestElement.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | 4 | class Solution: 5 | def quickSelect(self, a, l, r, index): 6 | q = self.randomPartition(a, l, r) 7 | if q == index: 8 | return a[q] 9 | else: 10 | return self.quickSelect(a, q + 1, r, index) if q < index else self.quickSelect(a, l, q - 1, index) 11 | 12 | def randomPartition(self, a, l, r): 13 | i = random.randint(l, r) 14 | a[i], a[r] = a[r], a[i] 15 | return self.partition(a, l, r) 16 | 17 | def partition(self, a, l, r): 18 | x = a[r] 19 | i = l - 1 20 | for j in range(l, r): 21 | if a[j] < x: 22 | i += 1 23 | a[i], a[j] = a[j], a[i] 24 | i += 1 25 | a[i], a[r] = a[r], a[i] 26 | return i 27 | 28 | def findKthLargest(self, nums, k): 29 | return self.quickSelect(nums, 0, len(nums) - 1, len(nums) - k) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L215_KthLargestElement.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findKthLargest(self, nums, k): 3 | realidx = len(nums) - k 4 | pivot = nums[0] 5 | pivotidx = 0 6 | right = [] 7 | left = [] 8 | for i in range(1, len(nums)): 9 | if nums[i] <= pivot: 10 | left.append(nums[i]) 11 | pivotidx += 1 12 | else: 13 | right.append(nums[i]) 14 | # print(pivotidx) 15 | if pivotidx == realidx: 16 | # print(pivot) 17 | return pivot 18 | elif pivotidx < realidx: 19 | # print('find the right part') 20 | # print(right) 21 | res = self.findKthLargest(right, k) 22 | else: 23 | # print('find the left part') 24 | # print(left) 25 | # print(k-len(nums[pivotidx:])) 26 | res = self.findKthLargest(left, k - len(right) - 1) 27 | return res 28 | 29 | 30 | sol = Solution() 31 | # res = sol.findKthLargest([3,2,3,1,2,4,5,5,6],4) 32 | # print(res) 33 | # res = sol.findKthLargest([3,2,1,5,6,4],2) 34 | # print(res) 35 | res = sol.findKthLargest([3, 4, 3, 2, 1, 45, 6, 3, 6, 2, 43, 53, 3, 2, 2], 3) 36 | print(res) 37 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L216_CombinationSumIII.py: -------------------------------------------------------------------------------- 1 | # this don't constrain the number we choose 2 | 3 | import copy 4 | class Solution: 5 | def combinationSum3(self, k, n): 6 | if sum([i for i in range(1,k+1)])>n: 7 | return [] 8 | element = [0]*k 9 | element[1] = 1 10 | element[k-1] = k 11 | result = [] 12 | while 3*element[0]+2 <= n: # stop process 13 | element[0] += 1 14 | if result != []: 15 | result.pop() 16 | element[k-1] = 100 17 | element[1] = element[0] 18 | while element[k-1] > element[k-2]: #stop every loop 19 | element[1] += 1 20 | for i in range(2,k-1): 21 | element[i] = element[i-1]+1 22 | element[k-1] = 0 23 | element[k-1] = n-sum(element) 24 | elements = copy.deepcopy(element) 25 | result.append(elements) 26 | result.pop() 27 | print(result) 28 | return result 29 | 30 | sol = Solution() 31 | sol.combinationSum3(3,17) 32 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L216_CombinationSumIII09.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combinationSum3(self, k, n): 3 | result = [] 4 | if k == 1 and n<=9: 5 | return n 6 | elif (k==1 and n>9) or (k==2 and n>=18): 7 | return [] 8 | elif n<18 and k==2: 9 | if n/2%1>=0.5: 10 | upper = int(n/2)+1 11 | else: 12 | upper = int(n/2) 13 | for i in range(max(1,n-9),upper): 14 | result.append([i,n-i]) 15 | elif k>=3: 16 | for m in range(1,10): 17 | if sum([m+i for i in range(k)]) <=n: 18 | rest = self.combinationSum3(k-1,n-m) 19 | print(rest) 20 | for element in rest: 21 | if m in element: 22 | continue 23 | else: 24 | element.insert(0, m) 25 | element.sort() 26 | if not (element in result): 27 | result.append(element) 28 | else: 29 | break 30 | return result 31 | 32 | sol = Solution() 33 | res = sol.combinationSum3(2,13) 34 | print(res) 35 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L222. Count Complete Tree Nodes.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countNodes(self, root: TreeNode) -> int: 3 | if not root: 4 | return 0 5 | 6 | stack,cnt = [root],1 7 | while stack: 8 | tmp = stack.pop(0) 9 | if tmp.left: 10 | stack.append(tmp.left) 11 | cnt += 1 12 | if tmp.right: 13 | stack.append(tmp.right) 14 | cnt += 1 15 | return cnt -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L230. Kth Smallest Element in a BST.py: -------------------------------------------------------------------------------- 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 | stack = self.preorder_traversal(root,[]) 11 | return stack[k-1] 12 | 13 | 14 | 15 | def preorder_traversal(self,root,res): 16 | if not root: 17 | return 18 | self.preorder_traversal(root.left,res) 19 | res.append(root.val) 20 | self.preorder_traversal(root.right,res) 21 | return res 22 | 23 | 24 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L231_PowerOf2.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | class Solution: 4 | def isPowerOfTwo(self, n): 5 | if n <= 0: 6 | return False 7 | k = math.log(n,2) 8 | if k%1 - 0 > 0.00000000000001: 9 | return False 10 | else: 11 | return True -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L235. Lowest Common Ancestor of a Binary Search Tree.py: -------------------------------------------------------------------------------- 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 | # 找到横跨在两个数值之间的元素就是LCA in BST 9 | class Solution: 10 | def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 11 | maxval, minval = max(p.val, q.val), min(p.val, q.val) 12 | if maxval >= root.val >= minval: 13 | return root 14 | elif maxval < root.val: 15 | root = root.left 16 | else: 17 | root = root.right 18 | 19 | return self.lowestCommonAncestor(root, p, q) 20 | 21 | 22 | from Debug_BST import list2Tree, PrintTree 23 | 24 | sol = Solution() 25 | data = [6, 2, 8, 0, 4, 7, 9, None, None, 3, 5] 26 | 27 | tree = list2Tree(data) 28 | printT = PrintTree() 29 | printT.printTree(tree) 30 | 31 | res = sol.lowestCommonAncestor(tree, TreeNode(2), TreeNode(8)) 32 | print(res.val) 33 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L238. Product of Array Except Self.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | # 分别计算这个数两边的累乘就可以获得结果 4 | class Solution: 5 | def productExceptSelf(self, nums): 6 | nlen = len(nums) 7 | a = Counter(nums) 8 | if a[0] > 1: 9 | return [0] * nlen 10 | 11 | premul, sufmul = [1], [1] 12 | for i in range(1, nlen): 13 | premul.append(premul[-1] * nums[i - 1]) # 还可以通过直接计算减少append的 开销 14 | for i in range(nlen - 1, 0, -1): 15 | sufmul.insert(0, sufmul[0] * nums[i]) 16 | # print('premul,sufmul', premul, sufmul) 17 | 18 | for i in range(nlen): 19 | premul[i] = premul[i] * sufmul[i] 20 | 21 | return premul 22 | 23 | 24 | sol = Solution() 25 | res = sol.productExceptSelf([1, 2, 3, 0, 2, 0, 4]) 26 | print(res) 27 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L240_Search2DMatrixdiscussion.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchMatrix(self, matrix, target): 3 | rows,cols,row,col = len(matrix),len(matrix[0]),0,len(matrix[0])-1 4 | while row < rows and col>=0: 5 | if target> matrix[row][col]: 6 | row += 1 7 | elif target< matrix[row][col]: 8 | col -= 1 9 | else: 10 | return True 11 | return False 12 | 13 | sol = Solution() 14 | # res = sol.searchMatrix([[1,4,7,11,15],[2,5,8,12,19], 15 | # [3,6,9,16,22],[10,13,14,17,24], 16 | # [18,21,23,26,30]],33) 17 | # print(res) 18 | # res = sol.searchMatrix([[25,28,33]],33) 19 | # print(res) 20 | # res = sol.searchMatrix([[-1,3]],1) 21 | # print(res) 22 | # res = sol.searchMatrix([[1,3,5,7,9],[2,4,6,8,10],[11,13,15,17,19],[12,14,16,18,20],[21,22,23,24,25]],13) 23 | # print(res) 24 | res = sol.searchMatrix([[-5]],-10) 25 | print(res) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L241_Different Ways to Add Parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def diffWaysToCompute(self, input): 3 | res = [] 4 | if input.isdigit(): 5 | return [int(input)] 6 | for i in range(len(input)): 7 | if input[i] in '+-*': 8 | res1 = self.diffWaysToCompute(input[:i]) 9 | res2 = self.diffWaysToCompute(input[i+1:]) 10 | for m in res1: 11 | for n in res2: 12 | if input[i] == '+': 13 | res.append(m+n) 14 | elif input[i] == '-': 15 | res.append(m-n) 16 | else: 17 | res.append(m*n) 18 | return res 19 | 20 | sol = Solution() 21 | res = sol.diffWaysToCompute("2-1-1") 22 | print(res) 23 | res = sol.diffWaysToCompute("2*3-4*5") 24 | print(res) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L24_Swap Nodes in Pairs.py: -------------------------------------------------------------------------------- 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: ListNode) -> ListNode: 9 | if not head or not head.next: 10 | return head 11 | else: 12 | first = head 13 | second = first.next 14 | afternode = second.next 15 | 16 | head = second 17 | head.next = first 18 | first.next = afternode 19 | 20 | while afternode and afternode.next: 21 | prevnode = first 22 | first,second = afternode,afternode.next 23 | afternode = second.next 24 | 25 | prevnode.next = second 26 | second.next = first 27 | first.next = afternode 28 | 29 | return head 30 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L26 Remove Duplicates from Sorted Array.py: -------------------------------------------------------------------------------- 1 | # class Solution: 2 | # def removeDuplicates(self, nums): 3 | # if nums == []: 4 | # return 0 5 | 6 | # listLen = len(nums) 7 | # i = listLen-2 8 | # pre = nums[-1] 9 | # returnLen = 1 10 | 11 | # while i>=0: 12 | # cur = nums[i] 13 | # if not cur == pre: 14 | # returnLen += 1 15 | # pre = nums[i] 16 | # else: 17 | # nums.pop(i) 18 | # pre = nums[i] 19 | # i -= 1 20 | 21 | 22 | # return returnLen 23 | 24 | class Solution: 25 | def removeDuplicates(self, nums): 26 | 27 | if len(nums) < 2: 28 | return len(nums) 29 | 30 | j = 0 31 | 32 | for num in nums[1:]: 33 | if num != nums[j]: 34 | j += 1 35 | nums[j] = num 36 | return j+1,nums 37 | 38 | sol = Solution() 39 | res,nums = sol.removeDuplicates([0,0,1,1,1,2,2,3,3,4]) 40 | print(res,nums) 41 | 42 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L274_HIndex.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hIndex(self, citations): 3 | if citations != []: # think about empty 4 | citations.sort(reverse=True) 5 | idx = 0 6 | while(idxmaxLen: 15 | maxLen = paLen 16 | 17 | if s[point] == '(': 18 | paLenStack.append(paLen) 19 | paLen = 0 20 | stack += 1 21 | elif s[point] == ')': 22 | if stack>0: 23 | stack -= 1 24 | paLen = paLen+2+paLenStack.pop(-1) 25 | else: 26 | # print(point,s[point]) 27 | paLen = 0 28 | # print('stack,paLen',stack,paLen) 29 | point += 1 30 | if paLen>maxLen: 31 | maxLen = paLen 32 | return maxLen 33 | 34 | sol = Solution() 35 | # print(sol.longestValidParentheses('(()))()()()')) 36 | # print(sol.longestValidParentheses("()(()")) 37 | print(sol.longestValidParentheses("(()))((()((()))))")) 38 | # print(sol.longestValidParentheses("(()))()()()()()(((((()))))))()()()(((()))(()()()()")) 39 | 40 | 41 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L324 Wiggle sort II.py: -------------------------------------------------------------------------------- 1 | 2 | # 把偶数位置插入排序后的较大部分,但是注意中间值会相近导致相邻不满足条件,因此就将大和较大,小和较小匹配 3 | class Solution: 4 | def wiggleSort(self, nums: list) -> None: 5 | """ 6 | Do not return anything, modify nums in-place instead. 7 | """ 8 | if nums: 9 | a = nums[:] 10 | a.sort(reverse=True) 11 | start = len(nums) // 2 12 | 13 | nums[::2], nums[1::2] = a[start:], a[:start] 14 | 15 | print(nums) 16 | 17 | 18 | # test 19 | def test(method, random_samples=False): 20 | # test settings 21 | times = 10 22 | 23 | sol = method() 24 | nums = [1, 4, 1, 5, 1, 6] 25 | nums = [2, 17, 13, 2, 7, 9, 10, 5, 14, 15] 26 | nums = [2, 3, 2, 2, 3, 3, 2, 3, 2] 27 | # nums = [1, 2, 1, 2, 1, 1, 2, 2, 1] 28 | print(nums, end=' ') 29 | sol.wiggleSort(nums) 30 | 31 | if random_samples: 32 | import random 33 | 34 | for _ in range(times): 35 | len1 = random.randint(0, 20) 36 | nums = [] 37 | for __ in range(len1): 38 | num1 = random.randint(1, 20) 39 | nums.append(num1) 40 | print(nums, end=' ') 41 | sol.wiggleSort(nums) 42 | 43 | 44 | test(Solution, True) 45 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L327_CountofRangeSum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countRangeSum(self, nums, lower, upper): 3 | 4 | count = 0 5 | if len(nums) == 1: 6 | if nums[0]>= lower and nums[0]<=upper: 7 | return count+1 8 | else: 9 | return count 10 | for i in range(1,len(nums)): 11 | self.countRangeSum(nums[:i],lower,upper) 12 | self.countRangeSum(nums[i:],lower,upper) 13 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L332_BurstBalloon.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def maxCoins(self, nums): 3 | res = 0 4 | while len(nums)>2: 5 | minNum = min(nums[1:-1]) 6 | minidx = nums.index(minNum) 7 | print(minNum) 8 | res += minNum*nums[minidx-1]*nums[minidx+1] 9 | print(res) 10 | nums.remove(minNum) 11 | print(nums) 12 | if nums[0] int: # 可以参考1376题,使用dfs做,这样不需要存储结果还能更快 3 | memoi = {} 4 | 5 | def helper(node, state): # calculate the max val this node'child can gain 6 | # print(node, state) 7 | def util(node, states): 8 | if node: 9 | if (node, state) in memoi: 10 | return memoi[(node, state)] 11 | 12 | val1, val2 = helper(node, 'w'), node.val + helper(node, 'b') 13 | tmp = [val1, max(val1, val2)]['w' in states] 14 | memoi[(node, state)] = tmp 15 | return tmp 16 | return 0 17 | 18 | res1, res2 = util(node.left, state), util(node.right, state) 19 | # print('res1, res2,memoi', res1, res2, memoi) 20 | 21 | return res1 + res2 22 | 23 | if root and root.val is not None: # 0 放在判断也是否定 24 | return max(helper(root, 'w'), root.val + helper(root, 'b')) 25 | elif root is None: 26 | return 0 27 | else: 28 | return 29 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L341. Flatten nested list iterator.py: -------------------------------------------------------------------------------- 1 | # 主要思想就是在是列表的时候展开加到所有缓存中,否则,返回 2 | class NestedIterator: 3 | def __init__(self, nestedList: list): 4 | self.queue = nestedList 5 | 6 | def next(self) -> int: 7 | ret = self.queue.pop(0) 8 | return ret 9 | 10 | def hasNext(self) -> bool: 11 | while len(self.queue) >= 1: 12 | if isinstance(self.queue[0], int): 13 | return True 14 | else: 15 | self.queue = self.queue[0] + self.queue[1:] 16 | return False 17 | 18 | 19 | # Your NestedIterator object will be instantiated and called as such: 20 | # i, v = NestedIterator(nestedList), [] 21 | sol = NestedIterator([[1, 1], 2, [1, 1]]) 22 | sol = NestedIterator([[1, [[[[[[[[[[[[]]]]]]]]]]]], 1], 2, [1, 1]]) 23 | while sol.hasNext(): 24 | print(sol.next()) 25 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L343. Integer Break.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/04_Algorithms/Leetcode/L343. Integer Break.py -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L347. Top K Frequent Elements.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | class Solution: 5 | def topKFrequent(self, nums, k: int): 6 | tmp = Counter(nums) 7 | print(tmp) 8 | 9 | tmplist = [] 10 | for key in tmp: 11 | tmplist.append((key, tmp[key])) 12 | tmplist.sort(key=lambda s: s[1], reverse= True) 13 | print(tmplist) 14 | 15 | ret = [] 16 | for i in range(k): 17 | ret.append(tmplist[i][0]) 18 | return ret 19 | 20 | 21 | # test 22 | def test(method, random_samples=False): 23 | # test settings 24 | times = 10 25 | 26 | sol = method() 27 | nums, k = [1, 1, 1, 2, 2, 3, 5], 2 28 | print(nums, end=' ') 29 | res = sol.topKFrequent(nums, k) 30 | print(' and the res is ', res) 31 | 32 | if random_samples: 33 | import random 34 | 35 | for _ in range(times): 36 | len1 = random.randint(0, 20) 37 | nums = [] 38 | for __ in range(len1): 39 | num1 = random.randint(1, 10) 40 | nums.append(num1) 41 | print(nums, end=' ') 42 | res = sol.topKFrequent(nums, 5) 43 | print(' and the res is ', res) 44 | 45 | 46 | test(Solution, True) 47 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L38 Count and Say.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | 3 | class Solution: 4 | def countAndSay(self, n: int) -> str: 5 | result = '1' 6 | 7 | for i in range(n-1): 8 | result = ''.join([str(len(list(group)))+str(digit) for digit, group in itertools.groupby(result)]) 9 | 10 | return result 11 | sol = Solution() 12 | print(sol.countAndSay(9)) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L39 Combination Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: 3 | def findCombo(candidates,target,index,combo): 4 | for i in range(index,len(candidates)): 5 | if candidates[i] > target: 6 | break 7 | return findCombo(candidates,target-candidates[i], i,combo) 8 | 9 | 10 | 11 | candidates = sorted(candidates) 12 | print(candidates) 13 | return findCombo -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L41 First Missing Positive.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def firstMissingPositive(self, nums): 3 | if nums == []: 4 | return 1 5 | maxval = max(nums) 6 | if maxval<=0: 7 | return 1 8 | 9 | 10 | for i in (i for i in range(1,maxval+2)): 11 | if not i in nums: 12 | return i 13 | 14 | sol = Solution() 15 | result = sol.firstMissingPositive([5]) 16 | print(result) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L410. Split Array Largest Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def splitArray(self, nums, m): 3 | l,h = max(nums),sum(nums) 4 | if m == len(nums): 5 | return l 6 | 7 | self.nums = nums 8 | 9 | def CountOfMedian(median): 10 | numsum,cnt = 0,0 11 | for num in nums: 12 | numsum += num 13 | # print('numsum',numsum) 14 | if numsum>median: 15 | cnt += 1 16 | numsum = num 17 | return cnt+1 18 | 19 | while l m: 23 | l = median+1 24 | else: 25 | h = median 26 | 27 | return l 28 | 29 | sol = Solution() 30 | # print(sol.splitArray([7,2,5,10,8],3)) 31 | print(sol.splitArray([7,5,6],3)) 32 | 33 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L416. partition equal subset sum.py: -------------------------------------------------------------------------------- 1 | # dp[i][W] 能否取到W等于sum(nums)/2 2 | class Solution: 3 | def canPartition(self, nums) -> bool: 4 | pvalset = set() 5 | target = sum(nums) / 2 6 | for num in nums: 7 | if pvalset: 8 | tmp = set() 9 | for ele in pvalset: 10 | tmp.add(num + ele) 11 | if abs(num + ele - target) < 1e-4: 12 | # print(num + ele, target) 13 | return True 14 | pvalset = pvalset.union(tmp) 15 | pvalset.add(num) 16 | if num == target: 17 | return True 18 | return False 19 | 20 | 21 | sol = Solution() 22 | # print(sol.canPartition([1, 5, 5, 11])) 23 | # print(sol.canPartition([1, 2, 3, 5])) 24 | print(sol.canPartition([1, 1])) 25 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L446_ArithmeticSlicesII-Subsequence.py: -------------------------------------------------------------------------------- 1 | def f(length): 2 | base = [0, 0, 0, 0, 0, 1, 1, 2, 2, 2] 3 | if length < len(base): 4 | return base[length] 5 | else: 6 | return f(int(length / 2)) + f(length - int(length / 2)) 7 | 8 | 9 | def relation(length): 10 | result = 0 11 | for k in range(3, length + 1): 12 | result += length - k + 1 + f(k) 13 | while length / 2 > 3: 14 | for k in range(3, int(length / 2) + 1): 15 | result += int(length / 2) - k + length - int(length / 2) - k 16 | length = length / 2 17 | print(result) 18 | 19 | 20 | for i in range(3, 11): 21 | relation(i) 22 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L446_official.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numberOfArithmeticSlices(self, A): 3 | lookup = {} 4 | 5 | for i, a in enumerate(A): 6 | if a in lookup: 7 | lookup[a].append(i) 8 | else: 9 | lookup[a] = [i] 10 | 11 | dp = [] 12 | for _ in range(len(A)): 13 | dp.append({}) 14 | 15 | for k, num in enumerate(A): 16 | for i in range(0, k): 17 | diff = A[k] - A[i] 18 | X = A[i] - diff 19 | if X in lookup: 20 | for index in lookup[X]: 21 | if index < i: 22 | dp[k][diff] = dp[k].get(diff, 0) + 1 23 | 24 | if diff in dp[i]: 25 | dp[k][diff] = dp[k].get(diff, 0) + dp[i][diff] 26 | 27 | res = 0 28 | for x in dp: 29 | for k in x: 30 | res += x[k] 31 | 32 | return res 33 | sol = Solution() 34 | sol.numberOfArithmeticSlices([2, 4, 6, 8, 10]) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L448. Find All Numbers Disappeared in an Array.py: -------------------------------------------------------------------------------- 1 | # 每次对于每个数字进行交换,换到它索引所在的位置,没有可换的就设置为0 2 | # 官方题解:不需要交换,碰到对应索引的就标注为负数,已经是负数的不再标注,最后看那些位置是正数就是没出现过的 3 | class Solution: 4 | def findDisappearedNumbers(self, nums): 5 | i = 0 6 | while i < len(nums): 7 | num1 = nums[i] 8 | num2 = nums[num1 - 1] 9 | 10 | if num1 == 0 or num1 == i + 1: 11 | i += 1 12 | continue 13 | 14 | if not num2 or num1 == num2: 15 | nums[i] = 0 16 | nums[num1 - 1] = num1 17 | else: 18 | nums[i], nums[num1 - 1] = num2, num1 19 | # print(nums) 20 | ret = [] 21 | for i in range(len(nums)): 22 | if nums[i] == 0: 23 | ret.append(i + 1) 24 | return ret 25 | 26 | 27 | sol = Solution() 28 | print(sol.findDisappearedNumbers([4, 3, 2, 7, 8, 2, 3, 1])) 29 | print(sol.findDisappearedNumbers([1, 1])) 30 | print(sol.findDisappearedNumbers([2, 2])) 31 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L46 Permutations.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def permute(self, nums): 3 | self.result = [] 4 | self.dfs(nums,[],self.result) 5 | 6 | def dfs(self, nums, prefix, result): 7 | if nums == []: 8 | self.result.append(prefix) 9 | else: 10 | for i in range(len(nums)): 11 | self.dfs(nums[0:i]+nums[i+1:],self.prefix+[nums[i]],self.result) 12 | 13 | import itertools 14 | 15 | class Solution: 16 | def permute(self, nums): 17 | res = [] 18 | if nums == []: 19 | return [[]] 20 | for i in itertools.permutations(nums, len(nums)): 21 | res.append(i) 22 | 23 | return res 24 | 25 | sol = Solution() 26 | result = sol.permute() 27 | print(result) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L47 Permutations II.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | 3 | class Solution: 4 | def permuteUnique(self, nums): 5 | res = set() 6 | if nums == []: 7 | return [[]] 8 | 9 | for i in itertools.permutations(nums, len(nums)): 10 | if not i in res: 11 | res.add(i) 12 | 13 | s = [] 14 | for val in res: 15 | s.append(list(val)) 16 | 17 | return s 18 | 19 | sol = Solution() 20 | # result = sol.permuteUnique([1,1,1,2,2]) 21 | result = sol.permuteUnique("eat") 22 | print(result) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L49 Group Anagrams.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def groupAnagrams(self, strs): 3 | Anagramdict = {} 4 | result = [] 5 | for strsingle in strs: 6 | string = list(strsingle) 7 | string.sort() 8 | string = ''.join(string) 9 | if string in Anagramdict: 10 | result[Anagramdict[string]].append(strsingle) 11 | else: 12 | Anagramdict[string] = len(result) 13 | result.append([strsingle]) 14 | # print(result) 15 | 16 | return result 17 | 18 | sol = Solution() 19 | res =sol.groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]) 20 | print(res) 21 | 22 | 23 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L50 Pow(x, n).py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def myPow(self, x,n): 3 | nnew = abs(n) 4 | 5 | if n < 0: 6 | return 1/self.fastPow(x,nnew) 7 | else: 8 | return self.fastPow(x,nnew) 9 | 10 | def fastPow(self, x,nnew): 11 | if nnew == 0: 12 | return 1 13 | 14 | elif nnew%2 == 1: 15 | return x*self.fastPow(x*x,nnew//2) 16 | else: 17 | return self.fastPow(x*x,nnew//2) 18 | 19 | sol = Solution() 20 | # res = sol.myPow(2,-10) 21 | 22 | res = sol.myPow(2.00000,-2147483648) 23 | print(res) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L509. Fibonacci Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def fib(self, N: int): 3 | if N < 0: 4 | return 5 | elif N < 2: 6 | return N 7 | a, b = 0, 1 8 | for i in range(2, N + 1): 9 | c = a + b 10 | a, b = b, c 11 | 12 | return c 13 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L53 Maximum Subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSubArray(self, nums): 3 | queue = [] 4 | maxval = -10000000 5 | queueSum = 0 6 | if max(nums)<0: 7 | return max(nums) 8 | for num in nums: 9 | if num+queueSum>0: 10 | queue.append(num) 11 | queueSum+=num 12 | if queueSum>maxval: 13 | maxval = queueSum 14 | else: 15 | queue = [] 16 | queueSum = 0 17 | 18 | return maxval if maxval>-10000000 else 0 19 | 20 | sol = Solution() 21 | # print(sol.maxSubArray([-2,1,-3,4,-1,2,1,-5,4])) 22 | # print(sol.maxSubArray([])) 23 | # print(sol.maxSubArray([-3,1,2,3,-4,3,4,-5,6,-2,-1,3,-2])) 24 | print(sol.maxSubArray([-1])) 25 | print(sol.maxSubArray([-8,-8,3,-8,-8])) 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L543. Diameter of Binary Tree.py: -------------------------------------------------------------------------------- 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 | 9 | class Solution: 10 | def diameterOfBinaryTree(self, root: TreeNode) -> int: 11 | self.diameter = 0 12 | 13 | if root: 14 | def helper(node): 15 | if not node: 16 | return 0 17 | leftdepth = helper(node.left) 18 | rightdepth = helper(node.right) 19 | 20 | self.diameter = max(self.diameter, rightdepth + leftdepth) 21 | return max(rightdepth, leftdepth) + 1 22 | 23 | helper(root) 24 | 25 | return self.diameter 26 | 27 | 28 | from Debug_BST import list2Tree, PrintTree 29 | 30 | sol = Solution() 31 | data = [8, None, 6, 10, 5, 7, 9, None, 1, 1, 1, 1, None, 1, 1, 1, 11] 32 | data = [None] 33 | 34 | tree = list2Tree(data) 35 | printT = PrintTree() 36 | printT.printTree(tree) 37 | 38 | res = sol.diameterOfBinaryTree(tree) 39 | print(res) 40 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L559_Maximumdepth.py: -------------------------------------------------------------------------------- 1 | """ 2 | class Node(object): 3 | def __init__(self, val, children): 4 | self.val = val 5 | self.children = children 6 | """ 7 | class Solution(object): 8 | def maxDepth(self, root): 9 | if not root: 10 | return 0 11 | stack = [[root,1]] 12 | mark = [] # already visited place 13 | alldepth = [] 14 | while stack: 15 | idx,depth = stack.pop() 16 | print('tree_node',idx.val) 17 | alldepth.append(depth) 18 | mark.append(idx) 19 | for child in idx.children: # ALL NEIGHBOR 20 | if not child in mark and child: 21 | stack.append([child,depth+1]) 22 | print('depth',depth) 23 | print('maxdepth',max(alldepth)) 24 | return max(alldepth) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L56 Merge Intervals.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def merge(self, intervals): 3 | if intervals == [] or intervals == [[]]: 4 | return intervals 5 | intervals = sorted(intervals,key = lambda val: val[0]) 6 | preStart,preEnd = intervals[0][0],intervals[0][1] 7 | count = 1 8 | for i in range(1,len(intervals)): 9 | if intervals[i][0]<=preEnd: 10 | if intervals[i][1]>=preEnd: 11 | intervals[count-1] = [preStart,intervals[i][1]] 12 | preEnd = intervals[i][1] 13 | 14 | else: 15 | intervals[count] = intervals[i] 16 | preStart,preEnd = intervals[i][0],intervals[i][1] 17 | count+=1 18 | 19 | return intervals[0:count] 20 | 21 | sol =Solution() 22 | # print(sol.merge([[1,3],[2,6],[8,10],[15,18]])) 23 | # print(sol.merge([[]])) 24 | # print(sol.merge([[1,4],[2,3]])) 25 | print(sol.merge([[1,2],[3,5],[6,7],[8,10],[12,16],[4,8]])) 26 | 27 | 28 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L57 Insert Interval.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def insert(self, intervals, newInterval): 3 | if intervals == [] or intervals == [[]]: 4 | intervals.append(newInterval) 5 | return intervals 6 | intervals.append(newInterval) 7 | 8 | return self.merge(intervals) 9 | 10 | 11 | def merge(self, intervals): 12 | if intervals == [] or intervals == [[]]: 13 | return intervals 14 | intervals = sorted(intervals,key = lambda val: val[0]) 15 | preStart,preEnd = intervals[0][0],intervals[0][1] 16 | count = 1 17 | for i in range(1,len(intervals)): 18 | if intervals[i][0]<=preEnd: 19 | if intervals[i][1]>=preEnd: 20 | intervals[count-1] = [preStart,intervals[i][1]] 21 | preEnd = intervals[i][1] 22 | 23 | else: 24 | intervals[count] = intervals[i] 25 | preStart,preEnd = intervals[i][0],intervals[i][1] 26 | count+=1 27 | 28 | return intervals[0:count] 29 | 30 | 31 | 32 | sol =Solution() 33 | # print(sol.merge([[1,3],[2,6],[8,10],[15,18]])) 34 | print(sol.insert([[]],[])) 35 | # print(sol.merge([[1,4],[2,3]])) 36 | print(sol.insert([[1,2],[3,5],[6,7],[8,10],[12,16]],[4,8])) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L58. Length of Last Word.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLastWord(self, s: str) -> int: 3 | if s == '' or s == ' ': 4 | return 0 5 | count,sLen = 0,len(s) 6 | lastStep = 0 7 | while s[sLen-1-lastStep] == ' ': 8 | lastStep += 1 9 | if lastStep == sLen -1 : 10 | break 11 | print(lastStep) 12 | 13 | while not s[sLen-count-1-lastStep] == ' ': 14 | count += 1 15 | if count == sLen: 16 | return count 17 | 18 | return count 19 | 20 | 21 | sol = Solution() 22 | print(sol.lengthOfLastWord(' a ')) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L59. Spiral Matrix II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generateMatrix(self, n): 3 | single = [0 for i in range(n)] 4 | matrix = [] 5 | for i in range(n): 6 | single = [] 7 | for j in range(n): 8 | single.append(0) 9 | matrix.append(single) 10 | 11 | orderList = ['right','down','left','up'] 12 | row,col = 0,0 13 | posSet = {(row,col)} 14 | matrix[row][col] = 1 15 | direction = 0 16 | for i in range(1, n**2): 17 | if direction == 0: 18 | row,col = row,col+1 19 | if col>=len(matrix[0]) or (row,col) in posSet: 20 | direction += 1 21 | row,col = row+1,col-1 22 | elif direction == 1: 23 | row,col = row+1,col 24 | if row>=len(matrix) or (row,col) in posSet: 25 | direction+=1 26 | row,col = row-1,col-1 27 | elif direction ==2: 28 | row,col = row,col-1 29 | if col<0 or (row,col) in posSet: 30 | direction+=1 31 | row,col = row-1,col+1 32 | else: 33 | row,col = row-1,col 34 | 35 | if (row,col) in posSet: 36 | direction = 0 37 | row,col = row+1,col+1 38 | posSet.add((row,col)) 39 | matrix[row][col] = i+1 40 | # print(matrix) 41 | 42 | return matrix 43 | 44 | sol = Solution() 45 | print(sol.generateMatrix(1)) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L5_LongestPalindromicSubstring.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | """Manacher""" 3 | def longestPalindrome(self, s): 4 | mx,ID = 0, 0 5 | stmp = '!&' 6 | for i in range(len(s)): 7 | stmp = stmp + s[i]+ '&' 8 | # print(stmp,s) 9 | p = [0 for i in range(len(stmp))] 10 | maxLen,maxID = 0,0 11 | 12 | 13 | for i in range(len(stmp)): 14 | if mx>i: 15 | # print(2*ID-1,len(stmp)) 16 | p[i] = min(p[2*ID-i],mx-i) 17 | else: 18 | p[i] = 1 19 | 20 | while (i-p[i]>0 and i+p[i] str: 5 | a = [str(i+1) for i in range(n)] 6 | for i,val in enumerate(itertools.permutations(a,n)): 7 | if i+1 == k: 8 | return ''.join(list(val)) 9 | 10 | sol = Solution() 11 | # print(sol.getPermutation(3,3)) 12 | print(sol.getPermutation(4,9)) 13 | print(sol.getPermutation(4,9)) 14 | 15 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L63. Unique Paths II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uniquePathsWithObstacles(self, obstacleGrid): 3 | if obstacleGrid == [] or obstacleGrid == [[]]: 4 | return 0 5 | 6 | m,n = len(obstacleGrid),len(obstacleGrid[0]) 7 | 8 | memoi = [[0]* n for _ in range(m)] 9 | for ii in range(n): 10 | if not obstacleGrid[0][ii] == 1: 11 | memoi[0][ii] = 1 12 | else: 13 | break 14 | 15 | for jj in range(m): 16 | if not obstacleGrid[jj][0] == 1: 17 | memoi[jj][0] = 1 18 | else: 19 | break 20 | 21 | if m >= 2 and n >=2: 22 | for i in range(1,m): 23 | for j in range(1,n): 24 | if obstacleGrid[i][j] == 1: 25 | memoi[i][j] = 0 26 | else: 27 | memoi[i][j] = memoi[i-1][j] + memoi[i][j-1] 28 | 29 | return memoi[-1][-1] 30 | 31 | 32 | sol = Solution() 33 | print(sol.uniquePathsWithObstacles([ 34 | [0,0,0], 35 | [0,1,0], 36 | [0,0,0] 37 | ])) 38 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L630_CourseScheduleiii.py: -------------------------------------------------------------------------------- 1 | # 选课问题,对于截止时间由先到后,如果前k个课程时间超出了最后一个截止时间,把时间最长的课程排除 2 | 3 | import heapq 4 | 5 | class Solution: 6 | def scheduleCourse(self, courses): 7 | start = 0 8 | heap = [] 9 | courses.sort(key = lambda x:x[1]) 10 | 11 | for length, end in courses: 12 | start += length 13 | heapq.heappush(heap,-length) 14 | print(heap) 15 | if start > end: 16 | print("need delete",heap) 17 | start = start + heapq.heappop(heap) #优先值最小的先pop出 18 | print(len(heap)) 19 | return len(heap) 20 | 21 | sol = Solution() 22 | sol.scheduleCourse([[100, 200], [200, 1300], [1000, 1250], [2000, 3200]]) 23 | sol.scheduleCourse([[5,5],[4,6],[2,6]]) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L630_CourseScheduleiiians.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | class Solution: 4 | def scheduleCourse(self, A): 5 | pq = [] # priority queue 6 | start = 0 7 | for t, end in sorted(A, key = lambda x:x[1]): 8 | start += t 9 | heapq.heappush(pq, -t) 10 | print(pq) 11 | while start > end: 12 | start += heapq.heappop(pq) 13 | print(pq) 14 | return len(pq) 15 | 16 | sol = Solution() 17 | sol.scheduleCourse([[100, 200], [200, 1300], [1000, 1250], [2000, 3200]]) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L637_AverageValPT.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def averageOfLevels(self, root): 3 | queue = [] 4 | rootlevel = 0 5 | res = [[] for _ in range(6000)] 6 | res[rootlevel].append(root.val) 7 | if root == None: 8 | return [] 9 | if root.left == None and root.right == None: 10 | return res[rootlevel] 11 | queue.append([root,rootlevel]) 12 | while queue != []: 13 | root,rootlevel = queue.pop() 14 | if root.left: 15 | res[rootlevel+1].append(root.left.val) 16 | queue.append([root.left,rootlevel+1]) 17 | if root.right: 18 | res[rootlevel+1].append(root.right.val) 19 | queue.append([root.right,rootlevel+1]) 20 | # print(res) 21 | averageVal = [] 22 | for sublist in res: 23 | if sublist!= []: 24 | if len(sublist) == 1: 25 | averageVal.append(sublist[0]) 26 | else: 27 | averageVal.append(sum(sublist)/len(sublist)) 28 | # print(averageVal) 29 | return averageVal -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L64. Minimum Path Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minPathSum(self, grid): 3 | if grid == [] or grid == [[]]: 4 | return 0 5 | m,n = len(grid),len(grid[0]) 6 | memoi = [[0]* n for _ in range(m)] 7 | for i in range(m): 8 | for j in range(n): 9 | if i == 0: 10 | if j == 0: 11 | memoi[i][j] = grid[i][j] 12 | else: 13 | memoi[i][j] = memoi[i][j-1]+grid[i][j] 14 | elif j == 0: 15 | memoi[i][j] = memoi[i-1][j]+grid[i][j] 16 | else: 17 | if memoi[i-1][j] List[int]: 3 | if digits[-1]<9: 4 | digits[-1] += 1 5 | else: 6 | ca,pos = 1,1 7 | while ca == 1: 8 | digits[-pos] = 0 9 | if pos == len(digits): 10 | digits.insert(0,1) 11 | break 12 | if not digits[-(pos+1)] == 9: 13 | ca = 0 14 | digits[-(pos+1)] += 1 15 | else: 16 | pos+=1 17 | return digits 18 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L662_maxWidthinBinaryTree.py: -------------------------------------------------------------------------------- 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 widthOfBinaryTree(self, root): 10 | if not root: 11 | return 0 12 | stack = [root,1] 13 | mark = [] # already visited place 14 | elementInEachLevel = [0] 15 | while stack: 16 | idx,depth = stack.pop() 17 | # print(idx) 18 | if len(elementInEachLevel) < depth: 19 | elementInEachLevel.append(1) 20 | else: 21 | elementInEachLevel[depth] += 1 22 | mark.append(idx) 23 | for child in [idx.left,idx.right]: # ALL NEIGHBOR 24 | if not child in mark: 25 | stack.append([child,depth+1]) 26 | print(max(elementInEachLevel)) 27 | return max(elementInEachLevel) 28 | 29 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L684_RedundentConnection.py: -------------------------------------------------------------------------------- 1 | ## 利用欧拉回路存在条件: 无向连通图中所有节点度为偶数 2 | # 首先去掉所有度为奇数的节点和链接,如果存在剩余节点,剩余节点成环 3 | # 输出边中包含两个剩余节点的最后一条边 4 | 5 | class Solution: 6 | def findRedundantConnection(self, edges): 7 | """ 8 | :type edges: List[List[int]] 9 | :rtype: List[int] 10 | """ 11 | # 找到所有节点的度 12 | point = {} #节点和节点之间的连接 13 | for i in range(edges): 14 | if point.__contains__(edges[i][0]): 15 | point[edges[i][0]].append(edges[i][1]) 16 | else: 17 | point[edges[i][0]] = [edges[i][1]] 18 | if point.__contains__(edges[i][1]): 19 | point[edges[i][1]].append(edges[i][0]) 20 | else: 21 | point[edges[i][1]] = [edges[i][0]] 22 | # 去除度为奇数的节点和其他联系 23 | for node in point.keys(): 24 | if len(point[node]) == 1: 25 | stack = [point[node]] 26 | while stack: 27 | pass 28 | for connectNode in point[node]: 29 | point[connectNode].remove(node) 30 | if len(point[connectNode]) == 1: 31 | pass 32 | 33 | point.pop(i) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L692.top-k-frequent-words.py: -------------------------------------------------------------------------------- 1 | # 使用set 统计词频,然后将词频加入到长度为k的优先队列进行排序 2 | import heapq 3 | 4 | class Solution: 5 | def topKFrequent(self, words: list, k: int) -> list: 6 | freqset = dict() 7 | for word in words: 8 | if word not in freqset.keys(): 9 | freqset[word] = 1 10 | else: 11 | freqset[word] += 1 12 | 13 | h = [(-freqset[ele], ele) for ele in freqset] 14 | heapq.heapify(h) 15 | ret = [] 16 | while len(ret) < k: 17 | ret.append(heapq.heappop(h)[1]) 18 | 19 | return ret 20 | 21 | 22 | sol = Solution() 23 | print(sol.topKFrequent(["a", "day", "is", "sunny", "a", "a", "sunny", "is", "is"], 4)) 24 | print(sol.topKFrequent(["i", "love", "leetcode", "i", "love", "coding"], 2)) 25 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L70_CllimingStairsinDP.py: -------------------------------------------------------------------------------- 1 | # 1-d dynamic programming 2 | # find number of ways to sum up to a number using given element 3 | # 4 | 5 | # assume key1 str: 3 | path = path.split('/') 4 | # print(path) 5 | res = [] 6 | for val in path: 7 | if val == '' or val == '.': 8 | continue 9 | elif val == '..': 10 | if len(res)>0: 11 | res.pop(-1) 12 | else: 13 | res.append(val) 14 | # print(res) 15 | resStr = '' 16 | if res==[]: 17 | res.append('') 18 | for item in res: 19 | resStr+='/'+item 20 | 21 | return resStr 22 | 23 | 24 | sol = Solution() 25 | # print(sol.simplifyPath("/a//b////c/d//././/..")) # /a/b/c 26 | # print(sol.simplifyPath("/a/../../b/../c//.//")) # "/c" 27 | # print(sol.simplifyPath("/a/./b/../../c/")) # "/c" 28 | # print(sol.simplifyPath("/home////")) # "/c" 29 | print(sol.simplifyPath("/../")) # "/c" 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L718. Maximum Length of Repeated Subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findLength(self, A, B): 3 | Alen,Blen = len(A),len(B) 4 | if not Alen or not Blen: 5 | return 0 6 | buff = [[0 for i in range(Blen+1)] for _ in range(Alen+1)] 7 | for aidx in range(1,Alen+1): 8 | for bidx in range(1,Blen+1): 9 | if A[aidx-1] == B[bidx-1]: 10 | print(aidx,bidx) 11 | buff[aidx][bidx] = buff[aidx-1][bidx-1]+1 12 | return max(max(row) for row in buff) 13 | 14 | sol = Solution() 15 | # print(sol.findLength([1,2,3,2,1,4,2,5,2,7,2,7,2,8,2,8],[3,2,1,4,7,4,2,3,1,2,5,7,4,8,4,5])) 16 | print(sol.findLength([1,2,3,2,1,4,3,6],[3,2,1,4,7])) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L72. Edit Distance.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minDistance(self, word1, word2): 3 | """Dynamic programming solution""" 4 | m = len(word1) 5 | n = len(word2) 6 | table = [[0] * (n + 1) for _ in range(m + 1)] 7 | 8 | for i in range(m + 1): 9 | table[i][0] = i 10 | for j in range(n + 1): 11 | table[0][j] = j 12 | 13 | for i in range(1, m + 1): 14 | for j in range(1, n + 1): 15 | if word1[i - 1] == word2[j - 1]: 16 | table[i][j] = table[i - 1][j - 1] 17 | else: 18 | table[i][j] = 1 + min(table[i - 1][j], table[i][j - 1], table[i - 1][j - 1]) 19 | return table[-1][-1] -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L73. Set Matrix Zeroes.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def setZeroes(self, matrix): 3 | """ 4 | Do not return anything, modify matrix in-place instead. 5 | """ 6 | m,n = len(matrix),len(matrix[0]) 7 | rowSet,colSet = set(),set() 8 | for i in range(m): 9 | for j in range(n): 10 | if matrix[i][j] == 0: 11 | rowSet.add(i) 12 | colSet.add(j) 13 | 14 | for row in rowSet: 15 | for j in range(n): 16 | matrix[row][j] = 0 17 | 18 | for i in range(m): 19 | for col in colSet: 20 | matrix[i][col] = 0 21 | 22 | print(matrix) 23 | 24 | sol = Solution() 25 | sol.setZeroes([ 26 | [0,1,2,0], 27 | [3,4,5,2], 28 | [1,3,1,5] 29 | ]) 30 | sol.setZeroes([ 31 | [1,1,1], 32 | [1,0,1], 33 | [1,1,1] 34 | ]) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L74. Search a 2D Matrix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchMatrix(self, matrix, target): 3 | if matrix == [[]] or matrix == []: 4 | return False 5 | NoRows,NoCols = len(matrix),len(matrix[0]) 6 | print(NoRows,NoCols) 7 | 8 | first = [] 9 | for i in range(NoRows): 10 | first.append(matrix[i][0]) 11 | 12 | for i in range(NoRows): 13 | if target <= first[i]: 14 | pos = i-1 15 | break 16 | elif i == NoRows-1: 17 | pos = NoRows-1 18 | 19 | 20 | 21 | if not pos == NoRows-1 and target == first[pos+1]: 22 | return True 23 | else: 24 | colPos = 0 25 | targetRow = matrix[pos] 26 | for j in range(NoCols): 27 | if targetRow[j] == target: 28 | return True 29 | 30 | return False 31 | 32 | 33 | 34 | sol = Solution() 35 | print(sol.searchMatrix([ [1, 3, 5, 7], 36 | [10, 11, 16, 20], 37 | [23, 30, 34, 50]],35)) 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L75. Sort Colors.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortColors(self, nums): 3 | """ 4 | Do not return anything, modify nums in-place instead. 5 | """ 6 | if nums == []: 7 | return nums 8 | zeroList,onelist,twolist = [],[],[] 9 | for num in nums: 10 | if num == 0: 11 | zeroList.append(0) 12 | elif num == 1: 13 | onelist.append(1) 14 | else: 15 | twolist.append(2) 16 | 17 | nums[:] = zeroList+onelist+twolist 18 | print(nums) 19 | 20 | 21 | sol =Solution() 22 | sol.sortColors([2,0,2,1,1,0]) 23 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L78. Subsets.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subsets(self, nums): 3 | nums = list(set(nums)) 4 | subsets = [[]] 5 | for n in nums: 6 | subsets += [s + [n] for s in subsets] 7 | return subsets 8 | 9 | 10 | 11 | 12 | sol = Solution() 13 | print(sol.subsets([1,1,3,2,1,2,1,1,2,1])) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L784_LetterPermutation.py: -------------------------------------------------------------------------------- 1 | import copy 2 | class Solution: 3 | def dp(self,s,i): 4 | if i>len(s)-1: 5 | self.b.append(s) 6 | print(s) 7 | else: 8 | print('inelse') 9 | if not s[i].isdigit(): 10 | print('isletter') 11 | string = copy.deepcopy(s[i]) 12 | if s[i]==string.lower(): 13 | print("islowerletter") 14 | self.dp(s,i+1) 15 | self.dp(s[:i]+s[i].upper()+s[i+1:],i+1) 16 | else: 17 | print("isupperletter") 18 | self.dp(s,i+1) 19 | self.dp(s[:i]+s[i].lower()+s[i+1:],i+1) 20 | else: 21 | print("isdigit") 22 | self.dp(s,i+1) 23 | return self.b 24 | 25 | def letterCasePermutation(self, S): 26 | self.b=[] 27 | result = self.dp(S,0) 28 | print(result) 29 | return result 30 | 31 | sol = Solution() 32 | sol.letterCasePermutation("a1b2") 33 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L7_reverseInteger.py: -------------------------------------------------------------------------------- 1 | # reverse an integer and return 0 if overflow 2 | 3 | class Solution: 4 | def reverse(self, x): 5 | if x>0: 6 | sign = 1 7 | else: 8 | sign = -1 9 | single = [] 10 | while x != 0: 11 | single.append(x%(10*sign)) 12 | x = int(x/10) 13 | reversedx = 0 14 | for i in range(len(single)): 15 | reversedx += single[-1]*(10**i) 16 | single.pop() 17 | if reversedx > 2**31 - 1 or reversedx<-2**31: 18 | return 0 19 | else: 20 | return reversedx 21 | 22 | def test(): 23 | sol = Solution() 24 | res = sol.reverse(-234) 25 | print(res) 26 | 27 | test() -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L80. Remove Duplicates from Sorted Array II.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeDuplicates(self, nums): 3 | duplicate = {} 4 | for i in range(len(nums)-1,-1,-1): 5 | if not nums[i] in duplicate: 6 | duplicate = {nums[i]:1} 7 | elif duplicate[nums[i]] == 1: 8 | duplicate[nums[i]] = 2 9 | else: 10 | del nums[i] 11 | return len(nums) 12 | 13 | sol = Solution() 14 | print(sol.removeDuplicates([])) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L814. Binary Tree Pruning.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, x): 3 | self.val = x 4 | self.left = None 5 | self.right = None 6 | 7 | 8 | # 后序遍历,如果没有孩子,自己是0,就删除 9 | class Solution: 10 | def pruneTree(self, root: TreeNode) -> TreeNode: 11 | 12 | def traverse(node): 13 | if not node: 14 | return node 15 | node.left = traverse(node.left) 16 | node.right = traverse(node.right) 17 | if node.val == 0 and not node.left and not node.right: 18 | return None 19 | else: 20 | return node 21 | 22 | root = traverse(root) 23 | 24 | return root 25 | 26 | 27 | from Debug_BST import list2Tree, PrintTree 28 | 29 | sol = Solution() 30 | data = [1, 1, 0, 0, 0, 0, 1] 31 | data = [0, 0, 0, 0, 0, 0, 0] 32 | data = [1, 0, 0, 0, 0, 0, 0] 33 | data = [1, 0, 1, 0, 1, 1, 0] 34 | data = [1, 1, 0, 1, 1, 0, 1, 0] 35 | data = [1, 0, 1, 0, 0, 0, 1] 36 | # data = [1] 37 | 38 | tree = list2Tree(data) 39 | printT = PrintTree() 40 | printT.printTree(tree) 41 | 42 | res = sol.pruneTree(tree) 43 | print(res) 44 | printT.printTree(res) 45 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L841_Key&Rooms.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canVisitAllRooms(self, rooms): 3 | startPoint = 0 4 | stack = [] 5 | stack.append(startPoint) 6 | mark = [] 7 | while stack: 8 | idx = stack.pop() 9 | # print(idx) 10 | mark.append(idx) 11 | for roomidx in rooms[idx]: 12 | if not roomidx>=len(rooms): 13 | if not roomidx in mark: 14 | stack.append(roomidx) 15 | if len(mark) < len(rooms): 16 | # print(False) 17 | return False 18 | else: 19 | # print(True) 20 | return True 21 | 22 | sol = Solution() 23 | sol.canVisitAllRooms([[1],[2],[3],[]]) 24 | sol.canVisitAllRooms([[1,3],[3,0,1],[2],[0]]) 25 | sol.canVisitAllRooms([[0]]) 26 | sol.canVisitAllRooms([[1],[4,5,3],[1,],[4]]) 27 | 28 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L84_LargestRect.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | 3 | # @ rtype: int 4 | def largestRectangleArea(self, heights): 5 | 6 | if heights==[] or heights==[[]]*len(heights): 7 | return 0 8 | areamax = heights[0] 9 | for i in range(len(heights)): 10 | areasum = 0 11 | minheight = heights[i] 12 | for j in range(i, len(heights)): 13 | if heights[j]areamax: 20 | areamax = areasum 21 | return areamax 22 | 23 | def test(): 24 | sol = Solution() 25 | res = sol.largestRectangleArea([2,1,5,6,2,3]) 26 | print(res) 27 | 28 | sol = Solution() 29 | res = sol.largestRectangleArea([3, 6, 5, 7, 4, 8, 1, 0]) 30 | print(res) 31 | 32 | test() 33 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L84_other.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestRectangleArea(self, height): 3 | height.append(0) 4 | stack = [-1] 5 | ans = 0 6 | for i in range(len(height)): 7 | while height[i] < height[stack[-1]]:#后面是不是比前面小 8 | h = height[stack.pop()] #小的话就拿出前面的高度,乘以累计几个高 9 | w = i - stack[-1] - 1 10 | print(h*w) 11 | ans = max(ans, h * w) 12 | stack.append(i) 13 | height.pop() 14 | return ans 15 | 16 | def test(): 17 | sol = Solution() 18 | res = sol.largestRectangleArea([2,1,5,6,2,3]) 19 | print(res) 20 | 21 | sol = Solution() 22 | res = sol.largestRectangleArea([3, 6, 5, 7, 4, 8, 1, 0]) 23 | print(res) 24 | 25 | test() 26 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L88. Merge Sorted Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def merge(self, nums1: list, m: int, nums2: list, n: int) -> None: 3 | """ 4 | Do not return anything, modify nums1 in-place instead. 5 | """ 6 | pnum1 = m - 1 7 | plist = m + n - 1 8 | pnum2 = n - 1 9 | while pnum1 >= 0 and pnum2 >= 0: 10 | if nums2[pnum2] > nums1[pnum1]: 11 | nums1[plist] = nums2[pnum2] 12 | pnum2 -= 1 13 | else: 14 | nums1[plist] = nums1[pnum1] 15 | pnum1 -= 1 16 | plist -= 1 17 | 18 | if pnum2 >= 0: 19 | nums1[:pnum2 + 1] = nums2[:pnum2 + 1] 20 | print(nums1) 21 | 22 | 23 | sol = Solution() 24 | print(sol.merge([1, 2, 3, 0, 0, 0], 3, [2, 5, 6], 3)) 25 | print(sol.merge([0, 0, 0], 0, [2, 5, 6], 3)) 26 | print(sol.merge([1, 2, 3], 3, [], 0)) 27 | print(sol.merge([], 0, [], 0)) 28 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L89. Gray Code.py: -------------------------------------------------------------------------------- 1 | # 按照镜面对称的方法构造格雷码,镜面对称只变换最前面一位,其他按照镜面对称,保证交替只变换一位 2 | 3 | class Solution: 4 | def grayCode(self, n: int): 5 | if n == 0: 6 | return [0] 7 | ret = ['0', '1'] 8 | for i in range(2, n + 1): 9 | pp = len(ret) 10 | for j in range(pp - 1, -1, -1): 11 | ret.append('1' + ret[j]) 12 | for j in range(pp): 13 | ret[j] = '0' + ret[j] 14 | print(ret) 15 | 16 | for i, ele in enumerate(ret): 17 | ret[i] = int(ele, base=2) 18 | 19 | return ret 20 | 21 | 22 | sol = Solution() 23 | print(sol.grayCode(3)) 24 | print(sol.grayCode(0)) 25 | print(sol.grayCode(1)) 26 | print(sol.grayCode(2)) 27 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L896_MonotonicArray.py: -------------------------------------------------------------------------------- 1 | import copy 2 | class Solution: 3 | def isMonotonic(self, A): 4 | d = copy.deepcopy(A) 5 | A.sort() 6 | sortA = copy.deepcopy(A) 7 | A.sort(reverse = True) 8 | resortA = copy.deepcopy(A) 9 | if d == sortA or d == resortA: 10 | return True 11 | else: 12 | return False 13 | sol = Solution() 14 | sol.isMonotonic([1,2,2,3]) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L921. Minimum Add to Make Parentheses Valid.py: -------------------------------------------------------------------------------- 1 | # 左括号前有右括号 2 | class Solution: 3 | def minAddToMakeValid(self, S: str) -> int: 4 | leftcnt, rightcnt = 0, 0 5 | for ele in S: 6 | if ele == '(': 7 | leftcnt += 1 8 | else: 9 | if leftcnt != 0: 10 | leftcnt -= 1 11 | else: 12 | rightcnt += 1 13 | return leftcnt + rightcnt 14 | 15 | 16 | sol = Solution() 17 | print(sol.minAddToMakeValid('())')) 18 | print(sol.minAddToMakeValid('')) 19 | print(sol.minAddToMakeValid('()))((')) 20 | print(sol.minAddToMakeValid('()')) 21 | print(sol.minAddToMakeValid('(())')) 22 | print(sol.minAddToMakeValid('(()))(')) 23 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L958. Check Completeness of a Binary Tree.py: -------------------------------------------------------------------------------- 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 | 9 | # 除了-1层,其他不能没有,-1层只要没有了就不能再有 10 | # BFS 层序遍历,加判断前面有没有出现过没有孩子的 11 | class Solution: 12 | def isCompleteTree(self, root: TreeNode) -> bool: 13 | if not root: 14 | return True 15 | 16 | queue = [root] 17 | nochild = False 18 | while queue: 19 | node = queue.pop(0) 20 | for nei in (node.left, node.right): 21 | if nochild: 22 | if nei: 23 | return False 24 | else: 25 | if not nei: 26 | nochild = True 27 | else: 28 | queue.append(nei) 29 | return True 30 | 31 | 32 | from Debug_BST import list2Tree, PrintTree 33 | 34 | sol = Solution() 35 | data = [8, 6, 10, 5, 7, 9, 11] 36 | data = [1, 2, 3, 4, 5, None, 7] 37 | data = [1] 38 | data = [1, 2, 3, 4, 2, 1, 4, None, None, 5] 39 | 40 | tree = list2Tree(data) 41 | printT = PrintTree() 42 | printT.printTree(tree) 43 | 44 | res = sol.isCompleteTree(tree) 45 | print(res) 46 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/L9_PalindromeNumber.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPalindrome(self, x) : 3 | if x<0: 4 | return False 5 | else: 6 | x = str(x) 7 | xlen = len(x) 8 | print(xlen) 9 | stop = xlen//2 10 | for i in range(stop): 11 | if x[i] != x[-(1+i)]: 12 | return False 13 | return True 14 | 15 | # palindrome is the one same as the it reverse self 16 | class Solution: 17 | def isPalindrome(self, x) : 18 | if x<0: 19 | return False 20 | else: 21 | x = str(x) 22 | return x == x[::-1] 23 | 24 | 25 | 26 | sol = Solution() 27 | res = sol.isPalindrome(122222222222222222222222222222222222222222221) 28 | # res = sol.isPalindrome(123) 29 | print(res) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/Lemons.py: -------------------------------------------------------------------------------- 1 | # a simple parser for python. use get_number() and get_word() to read 2 | def parser(): 3 | while 1: 4 | data = list(input().split(' ')) 5 | for number in data: 6 | if len(number) > 0: 7 | yield (number) 8 | 9 | 10 | input_parser = parser() 11 | 12 | 13 | def get_word(): 14 | global input_parser 15 | return next(input_parser) 16 | 17 | 18 | def get_number(): 19 | data = get_word() 20 | try: 21 | return int(data) 22 | except ValueError: 23 | return float(data) 24 | 25 | 26 | N, M, S = get_number(), get_number(), get_number() 27 | # N,M,S = 4,1,2 28 | 29 | travelCost = (N - 1) * M 30 | start, end, cnt = 2, N, 0 31 | # Binary search 32 | while start<= end: 33 | mid = (start + end) // 2 34 | start = mid + 1 35 | cnt += 1 36 | print('start,end,mid', start, end, mid) 37 | print('cnt', cnt) 38 | res = cnt * S 39 | 40 | print(res + travelCost) 41 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/Math_Attack and Speed.py: -------------------------------------------------------------------------------- 1 | # a simple parser for python. use get_number() and get_word() to read 2 | def parser(): 3 | while 1: 4 | data = list(input().split(' ')) 5 | for number in data: 6 | if len(number) > 0: 7 | yield(number) 8 | 9 | input_parser = parser() 10 | 11 | def get_word(): 12 | global input_parser 13 | return next(input_parser) 14 | 15 | def get_number(): 16 | data = get_word() 17 | try: 18 | return int(data) 19 | except ValueError: 20 | return float(data) 21 | 22 | 23 | A,S,K,X,Y = get_number(),get_number(),get_number(),get_number(),get_number() 24 | 25 | res = (S-A+K*Y)//(X+Y) 26 | if A +res*X == S+ (K-res)*Y: 27 | print(res) 28 | else: 29 | print(-1) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/Monotonic stack.py: -------------------------------------------------------------------------------- 1 | ## 单调栈stack,通过让栈中元素始终都维持递增,得到 2 | ## 数组中某个元素两侧比它小的值 3 | 4 | class Solution(object): 5 | def largestRectangleArea(self, height): 6 | if height == None: 7 | return 0 8 | stack = [] 9 | #添加-1是为了判断是不是进行到了最后一个 10 | height.append(-1) 11 | ans = 0 12 | for i in range(len(height)): 13 | cur = height[i] 14 | #如果栈为空或者当前柱比栈顶柱要高,入栈 15 | if len(stack) == 0 or cur >= height[stack[-1]]: 16 | stack.append(i) 17 | else: 18 | #如果栈不为空并且当前柱比栈顶柱要低,出栈,更新结果。 19 | while len(stack) != 0 and cur <= height[stack[-1]]: 20 | h = height[stack.pop()] 21 | left = stack[-1] if len(stack)!=0 else -1 22 | right = i 23 | ans = max(ans,h*(right-left-1)) 24 | stack.append(i) 25 | return ans -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/Octopuses with Watches.py: -------------------------------------------------------------------------------- 1 | # a simple parser for python. use get_number() and get_word() to read 2 | def parser(): 3 | while 1: 4 | data = list(input().split(' ')) 5 | for number in data: 6 | if len(number) > 0: 7 | yield(number) 8 | 9 | input_parser = parser() 10 | 11 | def get_word(): 12 | global input_parser 13 | return next(input_parser) 14 | 15 | def get_number(): 16 | data = get_word() 17 | try: 18 | return int(data) 19 | except ValueError: 20 | return float(data) 21 | 22 | # numpy and scipy are available for use 23 | import numpy 24 | import scipy 25 | 26 | n,m = get_number(),get_number() 27 | matrix = [[0 for j in range(m)] for _ in range(n)] 28 | for i in range(m): 29 | for j in range(n): 30 | matrix[i][j] == get_number()%3 31 | 32 | print(matrix) 33 | for i in range(m) 34 | 35 | res = a + b 36 | print(res) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/Read Input.py: -------------------------------------------------------------------------------- 1 | # a simple parser for python. use get_number() and get_word() to read 2 | def parser(): 3 | while 1: 4 | data = list(input().split(' ')) 5 | for number in data: 6 | if len(number) > 0: 7 | yield (number) 8 | 9 | 10 | input_parser = parser() 11 | 12 | 13 | def get_word(): 14 | global input_parser 15 | return next(input_parser) 16 | 17 | 18 | def get_number(): 19 | data = get_word() 20 | try: 21 | return int(data) 22 | except ValueError: 23 | return float(data) 24 | 25 | 26 | a = get_word() 27 | d, s, swws, dws, f = get_number(), get_number(), get_number(), get_number(), get_number() 28 | ad, ss, dss, wdws, qf = get_number(), get_word(), get_word(), get_number(), get_number() 29 | 30 | print(a) 31 | print(d, s, swws, dws, f) 32 | print(ad, ss, dss, wdws, qf) 33 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/Strictly Convex Pairs.py: -------------------------------------------------------------------------------- 1 | # a simple parser for python. use get_number() and get_word() to read 2 | def parser(): 3 | while 1: 4 | data = list(input().split(' ')) 5 | for number in data: 6 | if len(number) > 0: 7 | yield(number) 8 | 9 | input_parser = parser() 10 | 11 | def get_word(): 12 | global input_parser 13 | return next(input_parser) 14 | 15 | def get_number(): 16 | data = get_word() 17 | try: 18 | return int(data) 19 | except ValueError: 20 | return float(data) 21 | 22 | # 将点分为内外的点: 23 | # 内部的点: 两两配对都可以获得正确的结果 24 | # 外部的点:检查两两之间是否交叉,如果和polygon上直线交叉,结果-1 25 | 26 | 27 | 28 | a = get_number() 29 | b = get_number() 30 | 31 | res = a + b 32 | print(res) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/Threading.py: -------------------------------------------------------------------------------- 1 | import threading 2 | import time 3 | 4 | 5 | def job2(): 6 | global queue 7 | A = 0 8 | for i in range(10100): 9 | A += 1 10 | queue.append(A) 11 | 12 | 13 | if __name__ == '__main__': 14 | t1 = threading.Thread(target=job2) 15 | t2 = threading.Thread(target=job2) 16 | t3 = threading.Thread(target=job2) 17 | t4 = threading.Thread(target=job2) 18 | # lock = threading.Lock() 19 | 20 | start = time.time() 21 | A = 0 22 | for i in range(10100 * 4): 23 | A += 1 24 | print("A", A) 25 | 26 | print("time of t1", time.time() - start) 27 | start = time.time() 28 | A = 0 29 | queue = [] 30 | t1.start() 31 | t2.start() 32 | t3.start() 33 | t4.start() 34 | t4.join() 35 | for ele in queue: 36 | A += ele 37 | print(A) 38 | print('time of t2 is', time.time() - start) 39 | print('all done') 40 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/Xtreme Rappers.py: -------------------------------------------------------------------------------- 1 | import math 2 | import random 3 | 4 | def parser(): 5 | while 1: 6 | data = list(input().split(' ')) 7 | for number in data: 8 | if len(number) > 0: 9 | yield(number) 10 | 11 | input_parser = parser() 12 | 13 | def get_word(): 14 | global input_parser 15 | return next(input_parser) 16 | 17 | def get_number(): 18 | data = get_word() 19 | try: 20 | return int(data) 21 | except ValueError: 22 | return float(data) 23 | 24 | num1 = get_number() 25 | num2 = get_number() 26 | # num1,num2 = 4,3 27 | 28 | if num2 == 0 or num1 == 0: 29 | res = 0 30 | elif num1>2*num2 or num2>2*num1: 31 | res = min(num1,num2) 32 | else: 33 | maxval = math.floor((num1+num2)//3) 34 | minVal = math.ceil(max(num2,num1)//2) 35 | res = random.randint(minVal,maxval) 36 | print(res) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/Xtreme13.Alfa Pool.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def __init__(self): 3 | self.memoi = [1] 4 | self.mod = 10 ** 9 + 7 5 | 6 | def NbrofGames(self, points): 7 | for i in range(1, points + 1): 8 | cumsum = 1 9 | res = 0 10 | while i >= cumsum: 11 | res = (res + self.memoi[i - cumsum]) % self.mod 12 | cumsum = 2 * cumsum + 1 13 | 14 | self.memoi.append(res) 15 | # print(self.memoi) 16 | 17 | return self.memoi[points] 18 | 19 | 20 | testcases = int(input()) 21 | sol = Solution() 22 | sol.NbrofGames(10**5) 23 | for k in range(testcases): 24 | points = int(input()) 25 | if points == 0: 26 | print(1) 27 | else: 28 | print((2 * sol.memoi[points]) % sol.mod) 29 | 30 | sol = Solution() 31 | print(sol.NbrofGames(5)) 32 | sol = Solution() 33 | print(sol.NbrofGames(7)) 34 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/Xtreme13.Batchman and GCD.py: -------------------------------------------------------------------------------- 1 | # 对于 1, -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/Xtreme13.Factorial zeros.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def solve(self, b, z): 3 | culmul = 1 4 | target = '0' * z 5 | for i in range(2, 7*10**2): 6 | culmul *= i 7 | res = self.str_base(culmul, b) 8 | # print(res) 9 | if res[:z] == target and res[z] != '0': 10 | return i 11 | return -1 12 | 13 | def digit_to_char(self, digit): 14 | if digit < 10: 15 | return str(digit) 16 | return chr(ord('a') + digit - 10) 17 | 18 | def str_base(self, number, base): 19 | res = ['-', ''][number >= 0] 20 | d, m = divmod(number, base) 21 | res += self.digit_to_char(m) 22 | while d > 0: 23 | d, m = divmod(d, base) 24 | res = res + self.digit_to_char(m) 25 | return res 26 | 27 | 28 | T = int(input()) 29 | sol = Solution() 30 | for _ in range(T): 31 | base, zeros = list(map(int, input().strip().split(' '))) 32 | print(sol.solve(base, zeros)) 33 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/Xtreme13.Math challenge.py: -------------------------------------------------------------------------------- 1 | # 40 TLE*4 nze*2 OK*4 2 | 3 | import math 4 | from functools import reduce 5 | 6 | 7 | def fast_pow(under, exp): 8 | if under == 0: 9 | return 0 10 | elif under == 1: 11 | return 1 12 | else: 13 | if exp == 1: 14 | return under 15 | elif exp == 0: 16 | return 1 17 | elif exp % 2 == 1: 18 | res = under * fast_pow(under, (exp - 1) / 2) ** 2 19 | else: 20 | res = fast_pow(under, exp / 2) ** 2 21 | return res % (10 ** 9 + 7) 22 | 23 | 24 | def comb(n, m): 25 | if m == 0 or n == 0: 26 | return 1 27 | tmp = reduce(lambda x, y: x * y, [i for i in range(n - m + 1, n + 1)]) 28 | return tmp // math.factorial(m) 29 | 30 | 31 | N = int(input()) 32 | for _ in range(N): 33 | a, b, c = list(map(int, input().split(' '))) 34 | if a == 1: 35 | print(1) 36 | else: 37 | print(fast_pow(a, comb(b, c))) 38 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/Xtreme13.Ranged Alfa Pool.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def __init__(self): 3 | self.memoi = [1] 4 | self.mod = 10 ** 9 + 7 5 | 6 | def NbrofGames(self, points): 7 | for i in range(1, points + 1): 8 | cumsum = 1 9 | res = 0 10 | while i >= cumsum: 11 | res = (res + self.memoi[i - cumsum]) % self.mod 12 | cumsum = 2 * cumsum + 1 13 | 14 | self.memoi.append(res) 15 | # print(self.memoi) 16 | 17 | return self.memoi[points] 18 | 19 | def calrange(self, points): 20 | if points == 0: 21 | return 1 22 | else: 23 | return (2 * sol.memoi[points]) % sol.mod 24 | 25 | 26 | testcases = int(input()) 27 | sol = Solution() 28 | sol.NbrofGames(10 ** 6) 29 | for k in range(testcases): 30 | A, B = list(map(int, input().split(' '))) 31 | res = 0 32 | for i in range(A, B + 1): 33 | res += sol.calrange(i) 34 | print(res % sol.mod) 35 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/Xtreme13.Strictly Convex Pairs.py: -------------------------------------------------------------------------------- 1 | # 1. 每个点对形成线段L,对于所有顶点, 2 | # 2. 判断顶点是否在线段异侧(计算叉积判断异号) 3 | # 3. 有一个异侧则相交 4 | class Solution: 5 | def __init__(self,x): 6 | self.val = x 7 | 8 | def solve(self,): 9 | pass -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/Xtreme13.googloplex.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def mod(self, b, p, m): 3 | res = 1 4 | while p: 5 | if p % 2: 6 | res = res * b % m 7 | b = b * b % m 8 | p = p >> 1 9 | return res 10 | 11 | def calculate(self, X, Y): 12 | modular = 10 ** Y 13 | X = X % (modular) 14 | 15 | minres = self.mod(X, 10**100, modular) 16 | res = minres 17 | for _ in range(86399): 18 | res = (res * X) % modular 19 | if res < minres: 20 | minres = res 21 | 22 | return minres 23 | 24 | 25 | ncases = int(input()) 26 | sol = Solution() 27 | for k in range(ncases): 28 | distance, wormhole = list(map(int, input().split(' '))) 29 | print(sol.calculate(distance, wormhole)) 30 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/Yin Yang.py: -------------------------------------------------------------------------------- 1 | # a simple parser for python. use get_number() and get_word() to read 2 | def parser(): 3 | while 1: 4 | data = list(input().split(' ')) 5 | for number in data: 6 | if len(number) > 0: 7 | yield(number) 8 | 9 | input_parser = parser() 10 | 11 | def get_word(): 12 | global input_parser 13 | return next(input_parser) 14 | 15 | def get_number(): 16 | data = get_word() 17 | try: 18 | return int(data) 19 | except ValueError: 20 | return float(data) 21 | 22 | 23 | # Len = 10 #get_number() 24 | # res = ''.join(['yY' for _ in range(Len//2)]) 25 | 26 | # if Len %2 == 1: 27 | # res+='y' 28 | 29 | # print(res) 30 | 31 | 32 | import random 33 | Len = get_number() 34 | res = '' 35 | for i in range(Len): 36 | idx = random.randint(0,1) 37 | res += ['Y','y'][idx == 1] 38 | 39 | print(res) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/baidu01.py: -------------------------------------------------------------------------------- 1 | n, m = list(map(int, input().split())) 2 | mat = [] 3 | for _ in range(n): 4 | mat.append(list(map(int, input().split()))) 5 | 6 | if n == 0 and m == 0: 7 | print() 8 | else: 9 | for i in range(n): 10 | for j in range(m): 11 | cnt = 1 12 | tmp = mat[i][j] 13 | 14 | for (ii, jj) in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]: 15 | if not 0 <= ii < n or not 0 <= jj < m: 16 | continue 17 | else: 18 | cnt += 1 19 | tmp += mat[ii][jj] 20 | 21 | mat[i][j] = round(tmp / cnt) 22 | 23 | if j != m - 1: 24 | print(mat[i][j], end=' ') 25 | 26 | print(mat[i][-1]) 27 | 28 | # 2 2 29 | # 10 22 30 | # 30 40 -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/blacklist.TXT: -------------------------------------------------------------------------------- 1 | blacklist: 2 | 6. ZigZag Conversion Medium 1049 vs 3264 3 | 8. String to Integer (atoi) Medium 953 vs 6058 4 | 13. Roman to Integer Easy 1440 vs 2865 5 | 27. Remove Element 950 vs 2022 6 | 28. Implement strStr() 1037 vs 1490 7 | 29. Divide Two Integers 773 vs 3745 8 | 65. Valid Number hard 506 vs 3619 9 | 68. Text Justification hard 421 vs 1154 10 | 11 | todoList: 12 | 10. Regular Expression Matching 13 | 18. 4Sum 14 | 22. Generate Parentheses -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/contest03.py: -------------------------------------------------------------------------------- 1 | # time limit execed 2 | 3 | 4 | class Solution: 5 | def robot(self, command, obstacles, x, y): 6 | collapse,reach = False,False 7 | i,pos = 0,[0,0] 8 | while not (collapse or reach): 9 | commandnow = command[i] 10 | if commandnow == 'U': 11 | pos[1] += 1 12 | elif commandnow == 'R': 13 | pos[0] += 1 14 | 15 | if pos[0] == x and pos[1] == y: 16 | return True 17 | elif pos in obstacles: 18 | return False 19 | 20 | i += 1 21 | if i>= len(command): 22 | i = 0 23 | 24 | 25 | sol = Solution() 26 | print(sol.robot(command = 'URR',obstacles = [[2,2]],x = 344,y = 234)) 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/decorator.py: -------------------------------------------------------------------------------- 1 | import functools 2 | import time 3 | 4 | 5 | def log(text): 6 | def decorator(func): # 带参数的decorator, 7 | @functools.wraps(func) # 传入decorator的函数的属性如name等不发生改变(函数签名) 8 | def wrapper(*args, **kw): # 内部可以接受从最外层到最内层的参数 9 | print('let\'s see if I can use {} and {}'.format(args, kw)) 10 | print('%s %s():' % (text, func.__name__)) 11 | return func(*args, **kw) 12 | 13 | return wrapper 14 | 15 | return decorator 16 | 17 | 18 | @log('parames') # 借助python 的@语法,在函数定义的时候行使装饰器的作用 19 | def now(*args, **kwargs): # wrapper 内部还可传入各种参数,但是要保证now 中也传入 20 | print(time.time()) 21 | 22 | 23 | # now = log()(now) 24 | d = {'1': '4'} # 传入kw 要从dict 中解包 25 | now(*[1, 2, 3, 45], **d) # 现在调用now,等效于调用wrapper,并增强now的功能 26 | print(now.__name__) 27 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/dijksta Algor adj list.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | 4 | def calculate_distances(graph, starting_vertex): 5 | distances = {vertex: float('infinity') for vertex in graph} 6 | distances[starting_vertex] = 0 7 | 8 | pq = [(0, starting_vertex)] 9 | while len(pq) > 0: 10 | current_distance, current_vertex = heapq.heappop(pq) 11 | 12 | # 距离会多次加入,只考虑更小的,因为是堆,因此后面的其实一定会抛弃 13 | if current_distance > distances[current_vertex]: 14 | continue 15 | 16 | for neighbor, weight in graph[current_vertex].items(): 17 | distance = current_distance + weight 18 | 19 | # 只加入更小的边 20 | if distance < distances[neighbor]: 21 | distances[neighbor] = distance 22 | heapq.heappush(pq, (distance, neighbor)) 23 | 24 | return distances 25 | 26 | 27 | example_graph = { 28 | 'U': {'V': 2, 'W': 5, 'X': 1}, 29 | 'V': {'U': 2, 'X': 2, 'W': 3}, 30 | 'W': {'V': 3, 'U': 5, 'X': 3, 'Y': 1, 'Z': 5}, 31 | 'X': {'U': 1, 'V': 2, 'W': 3, 'Y': 1}, 32 | 'Y': {'X': 1, 'W': 1, 'Z': 1}, 33 | 'Z': {'W': 5, 'Y': 1}, 34 | } 35 | print(calculate_distances(example_graph, 'X')) 36 | # => {'U': 1, 'W': 2, 'V': 2, 'Y': 1, 'X': 0, 'Z': 2} -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/heap sort.py: -------------------------------------------------------------------------------- 1 | def heap_sort(lst): 2 | def sift_down(start, end): 3 | """最大堆调整""" 4 | root = start 5 | while True: 6 | child = 2 * root + 1 7 | if child > end: # 没有孩子 8 | break 9 | if child + 1 <= end and lst[child] < lst[child + 1]: # 左孩子小于右孩子 10 | child += 1 11 | if lst[root] < lst[child]: # 根小于孩子,那么交换并继续向下 12 | lst[root], lst[child] = lst[child], lst[root] 13 | root = child 14 | else: 15 | break 16 | 17 | # 从倒数第一层向上,查看是否满足最大堆性质,来创建最大堆 18 | for start in range((len(lst) - 2) // 2, -1, -1): 19 | sift_down(start, len(lst) - 1) 20 | 21 | # 每次交换最大和队尾元素,并维持堆进行堆排序 22 | for end in range(len(lst) - 1, 0, -1): 23 | lst[0], lst[end] = lst[end], lst[0] 24 | sift_down(0, end - 1) 25 | return lst 26 | 27 | 28 | if __name__ == "__main__": 29 | l = [9, 2, 1, 7, 6, 8, 5, 3, 4] 30 | print(heap_sort(l)) 31 | 32 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/in.txt: -------------------------------------------------------------------------------- 1 | 7 2 | 2 7 3 3 | 6 999 5000 4 | 4 17 4 5 | 13 23 2 6 | 0 30 13 7 | 24 28 5 8 | 1000 1000 5000 -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/kuangshi02.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | def road(weights): 5 | memoi = np.zeros(len(weights), len(weights[0])) 6 | 7 | def legal(coords): 8 | return len(weights) >= coords[0] >= 0 and len(weights[0]) >= coords[1] >= 0 9 | 10 | for row in range(len(weights)): 11 | for col in range(len(weights[0])): 12 | cur = weights[row][col] 13 | if row == 0 and col == 0: 14 | memoi[row][col] = cur 15 | else: 16 | up, left = (row - 1, col), (row, col - 1) 17 | res = float('inf') 18 | if legal(up): 19 | res = min(res, memoi[up[0]][up[1]] + cur) 20 | if legal(left): 21 | res = min(res, memoi[left[0]][left[1]] + cur) 22 | memoi[row][col] = res 23 | 24 | return memoi[-1][-1] 25 | 26 | 27 | a = [[1, 4, 3], [2, 3, 4], [4, 5, 1]] 28 | print(road(a)) 29 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/lqw.py: -------------------------------------------------------------------------------- 1 | # 2 | # reverse string 3 | # @param str string字符串 the stirng 4 | # @return string字符串 5 | # 6 | class Solution: 7 | def reverseStringI(self, string): 8 | if not string: 9 | return string 10 | words = [] 11 | pre = 0 12 | for i, ele in enumerate(string): 13 | if ele == ' ': 14 | if (i - 1) >= 0 and string[i - 1] != ' ': 15 | words.append(string[pre:i]) 16 | pre = i + 1 17 | words.append(string[pre:]) 18 | 19 | for i, word in enumerate(words): 20 | tmp = '' 21 | for ele in word[::-1]: 22 | tmp += ele 23 | words[i] = tmp + ' ' 24 | ret = ''.join(words) 25 | 26 | return ret[:-1] 27 | 28 | sol = Solution() 29 | print(sol.reverseStringI("i am a student")) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/multiProcessing.py: -------------------------------------------------------------------------------- 1 | import multiprocessing as mp 2 | 3 | 4 | def job1(A, num, l): 5 | l.acquire() # 取消锁之后,导致进程开始前后不同,p2先开始了,但是数值依旧没有抢夺 6 | if num == 1: 7 | print('p1 start') 8 | else: 9 | print('p2 start') 10 | 11 | for i in range(10): 12 | print(A.value) 13 | A.value += num 14 | 15 | if num == 1: 16 | print('p1 finish') 17 | else: 18 | print('p2 finish ') 19 | l.release() 20 | 21 | 22 | if __name__ == '__main__': 23 | A = mp.Value('i', 1) 24 | lock = mp.Lock() 25 | p1 = mp.Process(target=job1, args=(A, 3, lock,)) # 没有出现数值抢夺 26 | p2 = mp.Process(target=job1, args=(A, 1, lock,)) 27 | p1.start() 28 | p2.start() # 在p1 结束之后才开始 29 | # p1.join() 30 | # p2.join() 31 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/multiProcessingVSmthreading.py: -------------------------------------------------------------------------------- 1 | import multiprocessing as mp 2 | import time 3 | import threading 4 | 5 | 6 | def job(q): 7 | res = 0 8 | for i in range(10000): 9 | res += i ** 2 10 | q.put(res) 11 | 12 | 13 | def multithread(): 14 | q = mp.Queue() 15 | t1 = threading.Thread(target=job, args=(q,)) 16 | t2 = threading.Thread(target=job, args=(q,)) 17 | t1.start() 18 | t2.start() 19 | t1.join() 20 | t2.join() 21 | print('thread', q.get()+q.get()) 22 | 23 | 24 | def multicore(): 25 | q = mp.Queue() 26 | p1 = mp.Process(target=job, args=(q,)) 27 | p2 = mp.Process(target=job, args=(q,)) 28 | p1.start() 29 | p2.start() 30 | p1.join() 31 | p2.join() 32 | print('process', q.get()+q.get()) 33 | 34 | 35 | def normal(): 36 | res = 0 37 | for _ in range(2): 38 | for i in range(10000): 39 | res += i ** 2 40 | 41 | print('normal', res) 42 | 43 | 44 | if __name__ == '__main__': 45 | start = time.time() 46 | normal() 47 | print('normal', time.time() - start) 48 | start = time.time() 49 | multicore() 50 | print('multicore', time.time() - start) 51 | start = time.time() 52 | multithread() 53 | print('multithread', time.time() - start) 54 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/mylist.py: -------------------------------------------------------------------------------- 1 | class MyList(object): 2 | def __init__(self, data): 3 | self.data = data 4 | self.idx = -1 5 | 6 | def __new__(cls, *args, **kwargs): 7 | pass 8 | 9 | def __iter__(self): 10 | return self # 实例本身就是迭代对象,故返回自己 11 | 12 | def __next__(self): 13 | self.idx += 1 14 | if self.idx >= len(self.data): # 退出循环的条件 15 | raise StopIteration() 16 | return self.data[self.idx] 17 | 18 | def __getitem__(self, item): 19 | if isinstance(item, int): 20 | return self.data[item] 21 | elif isinstance(item, slice): 22 | start = item.start 23 | stop = item.stop 24 | step = item.step 25 | if start is None: 26 | start = 0 27 | if step is None: 28 | step = 1 29 | print(item) 30 | 31 | L = [] 32 | for i in range(start, stop, step): 33 | L.append(self.data[i]) 34 | 35 | return L 36 | 37 | 38 | c: MyList = MyList((1, 2, 3, 4, 2, 1, 3, 2, 3, 1, 3, 5, 6, 7, 4, 2)) 39 | print(c[1], c[1:10], c[1:12:2], c[1:13:-1], c[:10:2]) 40 | for ele in c: 41 | print(ele) 42 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/priorityQueue.py: -------------------------------------------------------------------------------- 1 | from queue import PriorityQueue 2 | 3 | q = PriorityQueue() 4 | 5 | class ListNode: 6 | def __init__(self, x): 7 | self.val = x 8 | self.next = None 9 | 10 | q.put((2, ListNode(2))) 11 | q.put((1, ListNode(1))) 12 | q.put((3, ListNode(3))) 13 | 14 | while not q.empty(): 15 | next_item = q.get() 16 | print(next_item) -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/property&setter.py: -------------------------------------------------------------------------------- 1 | class Student(object): 2 | 3 | def __init__(self): 4 | self._score = 60 5 | 6 | @property # 设置score 读取的方法为一个属性 7 | def score(self): 8 | return self._score 9 | 10 | @score.setter # property.setter 使得property 可以写入 11 | def score(self, value): 12 | if not isinstance(value, int): 13 | raise ValueError('score must be an integer!') 14 | if value < 0 or value > 100: 15 | raise ValueError('score must between 0 ~ 100!') 16 | self._score = value 17 | 18 | 19 | s = Student() 20 | # s.score = 60 #类内封装的属性也可以直接访问了,转化为s.set_score(60) 21 | print(s.score) # 实际转化为s.get_score() 22 | s.score = 9999 # 实现了参数检查 -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/tenary search.py: -------------------------------------------------------------------------------- 1 | # Python3 program to illustrate 2 | # recursive approach to ternary search 3 | 4 | # Function to perform Ternary Search 5 | def ternarySearch(l, r, key, ar): 6 | if (r >= l): 7 | # Find the mid1 and mid2 8 | mid1 = l + (r - l) //3 9 | mid2 = r - (r - l) //3 10 | 11 | # Check if key is present at any mid 12 | if (ar[mid1] == key): 13 | return mid1 14 | 15 | if (ar[mid2] == key): 16 | return mid2 17 | 18 | if (key < ar[mid1]): 19 | return ternarySearch(l, mid1 - 1, key, ar) 20 | elif (key > ar[mid2]): 21 | return ternarySearch(mid2 + 1, r, key, ar) 22 | else: 23 | return ternarySearch(mid1 + 1, 24 | mid2 - 1, key, ar) 25 | return -1 26 | 27 | 28 | # Get the array sorted 29 | ar = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] 30 | 31 | # Starting index 32 | l = 0 33 | # length of array 34 | r = 9 35 | # Key to be searched in the array 36 | key = 5 37 | 38 | # Search the key using ternarySearch 39 | p = ternarySearch(l, r, key, ar) 40 | print("Index of", key, "is", p) 41 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/tencent 翻转数组的前n项和.py: -------------------------------------------------------------------------------- 1 | # tencent 2018春招 01 2 | # n, m = list(map(int, input().split(' '))) 3 | # pairs = n//(2*m) 4 | # print(pairs*m*m) 5 | 6 | # tencent 2018春招 02 7 | # length = int(input()) 8 | # data = list(map(int, input().split())) 9 | # data.sort(reverse=True) 10 | # # print(data) 11 | # niucnt, yangcnt = 0, 0 12 | # for i in range(0, length, 2): 13 | # niucnt += data[i] 14 | # if i + 1 < length: 15 | # yangcnt += data[i + 1] 16 | # print(niucnt - yangcnt) 17 | 18 | # tencent 2018春招 03 19 | 20 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/ttees.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | import numpy as np 4 | 5 | 6 | def focal_loss(logit, target, alpha, gamma): 7 | # logit: shape N C 8 | # target shape N 9 | p = logit[:][target] 10 | ret = sum((1 - p) ** gamma * alpha * math.log(p)) 11 | return ret 12 | 13 | 14 | lodit = np.array([[0, 1, 0, 1, 0, 5, 0, 4], 15 | [0, 1, 0, 1, 0, 5, 0, 4], 16 | [0, 1, 0, 1, 0, 5, 0, 4]]) 17 | target = np.array([1, 2, 3]) 18 | 19 | print(focal_loss(lodit, target, 0.4, 0.9)) 20 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/ziji04.py: -------------------------------------------------------------------------------- 1 | n, m = map(int, input().split()) 2 | nums = list(map(int, input().split())) 3 | for num in nums: 4 | num = num % m 5 | 6 | 7 | # nums.sort() 8 | def helper(i, cursum): 9 | global res 10 | res = max(res, cursum % m) 11 | if i <= n - 1: 12 | if nums[i] == 0: 13 | helper(i + 1, cursum) 14 | else: 15 | helper(i + 1, cursum) 16 | helper(i + 1, cursum + nums[i]) 17 | else: 18 | return 19 | 20 | 21 | res = 0 22 | helper(0, 0) 23 | print(res) 24 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/zijie02new.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | 3 | n, k = map(int, input().split(' ')) 4 | remaindict = {} 5 | data = list(map(int, input().split(' '))) 6 | 7 | cnt = 1 8 | if len(data) > 1: 9 | cnt += n 10 | # print(cnt) 11 | for i in range(2, len(data)): 12 | res = itertools.combinations(data, i) 13 | for combs in res: 14 | eleset = set() 15 | flag = False 16 | for ele in combs: 17 | if not ele%k in eleset: 18 | eleset.add(k - ele % k) 19 | else: 20 | flag = True 21 | break 22 | if not flag: 23 | cnt += 1 24 | # print(combs,cnt) 25 | print(cnt) 26 | 27 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/协程.py: -------------------------------------------------------------------------------- 1 | def consumer(): 2 | r = '' 3 | while True: 4 | n = yield r 5 | if not n: 6 | return 7 | print('[CONSUMER] Consuming %s...' % n) 8 | r = '200 OK' 9 | 10 | 11 | def produce(c): 12 | c.send(None) 13 | n = 0 14 | while n < 5: 15 | n = n + 1 16 | print('[PRODUCER] Producing %s...' % n) 17 | r = c.send(n) # 发送生产的东西给消费者,不需要通过线程之间的锁机制切换 18 | print('[PRODUCER] Consumer return: %s' % r) 19 | c.close() # 不生产了,停用generator 20 | 21 | 22 | customer = consumer() 23 | produce(customer) 24 | -------------------------------------------------------------------------------- /04_Algorithms/Leetcode/面试题 03.05. Sort of Stacks LCCI_stack.py: -------------------------------------------------------------------------------- 1 | class SortedStack: 2 | 3 | def __init__(self): 4 | self.data = [] 5 | self.help = [] 6 | 7 | def push(self, val: int) -> None: 8 | if self.data and self.data[-1] < val: 9 | while self.data and self.data[-1] < val: 10 | self.help.append(self.data.pop(-1)) 11 | self.data.append(val) 12 | while self.help: 13 | self.data.append(self.help.pop(-1)) 14 | # print(self.data) 15 | 16 | def pop(self) -> None: 17 | if not self.isEmpty(): 18 | self.data.pop(-1) 19 | 20 | def peek(self) -> int: 21 | if self.isEmpty(): 22 | return -1 23 | return self.data[-1] 24 | 25 | def isEmpty(self) -> bool: 26 | return not self.data 27 | 28 | 29 | obj = SortedStack() 30 | obj.push(1) 31 | obj.push(3) 32 | obj.push(2) 33 | obj.push(0) 34 | obj.pop() 35 | print(obj.peek()) 36 | obj.pop() 37 | print(obj.peek()) 38 | obj.pop() 39 | print(obj.peek()) 40 | obj.pop() 41 | print(obj.peek()) 42 | obj.pop() 43 | print(obj.peek()) 44 | print(obj.isEmpty()) 45 | -------------------------------------------------------------------------------- /04_Algorithms/README.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "collapsed": true, 7 | "pycharm": { 8 | "name": "#%% md\n" 9 | } 10 | }, 11 | "source": [ 12 | "# 主要算法总结\n", 13 | "根据CS97SI 课程整理相关知识,并辅助以leetcode中有疑惑的算法题解析进行讨论\n", 14 | "\n", 15 | "根据CS 97SI 总结的笔记,以及 python 语法笔记,在[这里](https://www.notion.so/shiyu00daisy/Xtreme-0f9c9b3264ea4126b02dc89224d6a524) \n", 16 | "\n" 17 | ] 18 | } 19 | ], 20 | "metadata": { 21 | "kernelspec": { 22 | "display_name": "Python 3", 23 | "language": "python", 24 | "name": "python3" 25 | }, 26 | "language_info": { 27 | "codemirror_mode": { 28 | "name": "ipython", 29 | "version": 3 30 | }, 31 | "file_extension": ".py", 32 | "mimetype": "text/x-python", 33 | "name": "python", 34 | "nbconvert_exporter": "python", 35 | "pygments_lexer": "ipython3", 36 | "version": "3.6.5" 37 | } 38 | }, 39 | "nbformat": 4, 40 | "nbformat_minor": 1 41 | } 42 | -------------------------------------------------------------------------------- /04_Algorithms/README.md: -------------------------------------------------------------------------------- 1 | 2 | # 主要算法总结 3 | 根据斯坦福 CS97SI 课程整理相关知识,并辅助以leetcode中有疑惑的算法题解析进行讨论 4 | 5 | 根据CS 97SI 总结的笔记,以及 python 语法笔记,在[这里](https://www.notion.so/shiyu00daisy/Xtreme-0f9c9b3264ea4126b02dc89224d6a524) 6 | -------------------------------------------------------------------------------- /05_Language/README.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "collapsed": true, 7 | "pycharm": { 8 | "name": "#%% md\n" 9 | } 10 | }, 11 | "source": [ 12 | "# Python等计算机语言\n", 13 | "这部分主要有一个大概框架来汇总语法糖和语言中常见的机制内部实现等\n" 14 | ] 15 | } 16 | ], 17 | "metadata": { 18 | "kernelspec": { 19 | "display_name": "Python 3", 20 | "language": "python", 21 | "name": "python3" 22 | }, 23 | "language_info": { 24 | "codemirror_mode": { 25 | "name": "ipython", 26 | "version": 2 27 | }, 28 | "file_extension": ".py", 29 | "mimetype": "text/x-python", 30 | "name": "python", 31 | "nbconvert_exporter": "python", 32 | "pygments_lexer": "ipython2", 33 | "version": "2.7.6" 34 | } 35 | }, 36 | "nbformat": 4, 37 | "nbformat_minor": 0 38 | } -------------------------------------------------------------------------------- /05_Language/README.md: -------------------------------------------------------------------------------- 1 | 2 | # Python等计算机语言 3 | 这部分主要有一个大概框架来汇总语法糖和语言中常见的机制内部实现等 4 | 5 | -------------------------------------------------------------------------------- /06_DL_framework/README.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "collapsed": true, 7 | "pycharm": { 8 | "name": "#%% md\n" 9 | } 10 | }, 11 | "source": [ 12 | "# 深度学习框架\n", 13 | "总结深度学习框架:pytorch,tensorflow等中的语法和机制\n", 14 | "\n", 15 | "根据[深度学习框架pytorch 入门与实践](https://github.com/chenyuntc/pytorch-book) 的结构总结+[网页](https://pytorch.apachecn.org/docs/1.2/intermediate/model_parallel_tutorial.html)\n", 16 | "\n", 17 | "\n" 18 | ] 19 | } 20 | ], 21 | "metadata": { 22 | "kernelspec": { 23 | "display_name": "Python 3", 24 | "language": "python", 25 | "name": "python3" 26 | }, 27 | "language_info": { 28 | "codemirror_mode": { 29 | "name": "ipython", 30 | "version": 3 31 | }, 32 | "file_extension": ".py", 33 | "mimetype": "text/x-python", 34 | "name": "python", 35 | "nbconvert_exporter": "python", 36 | "pygments_lexer": "ipython3", 37 | "version": "3.6.5" 38 | } 39 | }, 40 | "nbformat": 4, 41 | "nbformat_minor": 1 42 | } 43 | -------------------------------------------------------------------------------- /06_DL_framework/README.md: -------------------------------------------------------------------------------- 1 | 2 | # 深度学习框架 3 | 总结深度学习框架:pytorch,tensorflow等中的语法和机制 4 | 5 | 根据[深度学习框架pytorch 入门与实践](https://github.com/chenyuntc/pytorch-book) 的结构总结+[网页](https://pytorch.apachecn.org/docs/1.2/intermediate/model_parallel_tutorial.html) 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/CEderivative.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/CEderivative.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/FCN.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/FCN.jpg -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/GB.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/GB.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/KKT.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/KKT.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/MSEderivative.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/MSEderivative.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/SVM.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/SVM.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/Segnet.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/Segnet.jpg -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/Unet.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/Unet.jpg -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/Untitled 1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/Untitled 1.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/Untitled 2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/Untitled 2.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/Untitled 3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/Untitled 3.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/Untitled 4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/Untitled 4.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/Untitled 5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/Untitled 5.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/Untitled 6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/Untitled 6.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/Untitled 7.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/Untitled 7.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/Untitled.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/Untitled.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/basicbottle.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/basicbottle.jpg -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/cascade-RCNN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/cascade-RCNN.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/complementary.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/complementary.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/convCompute.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/convCompute.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/deeplabv3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/deeplabv3.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/detection.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/detection.jpg -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/detrans.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/detrans.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/dialated.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/dialated.gif -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/dp_0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/dp_0.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/dp_1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/dp_1.jpg -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/dropconnect.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/dropconnect.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/dropout.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/dropout.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/gk.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/gk.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/hough.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/hough.jpg -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/inout.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/inout.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/laplace.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/laplace.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/laplace_e.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/laplace_e.jpg -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/max_pooling.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/max_pooling.jpeg -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/mean_pooling.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/mean_pooling.jpeg -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/mr_f1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/mr_f1.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/n.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/n.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/overlap.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/overlap.jpg -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/psp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/psp.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/relu.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/relu.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/samplebias.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/samplebias.jpg -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/sobel.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/sobel.jpg -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/sobel_2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/sobel_2.jpg -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/softmargin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/softmargin.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/stacking.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/stacking.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/transequa.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/transequa.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/transposed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/transposed.png -------------------------------------------------------------------------------- /07_Interview_Questions/Pics/transposed_result.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shiyutang/DL-Prep/3e6565527ee8479e178852fffc4ccd0e44166e48/07_Interview_Questions/Pics/transposed_result.gif --------------------------------------------------------------------------------