├── 1-9 ├── 1. longestPalindromeSubstring(Medium) │ ├── README.md │ └── longestPalindrome.py ├── 2. findMidianSortedArrays(Hard) │ ├── README.md │ └── findMidianSortedArrays.py ├── 3. longestSubstringWithoutRepeating(Medium) │ ├── README.md │ └── lengthOfLongestSubstring.py ├── 4. stringToInteger(atio)(Medium) │ ├── README.md │ └── atio.py ├── 5. palindromeNumber(Easy) │ ├── README.md │ └── isNumberPalindrome.py ├── 6. mergeTwoBinaryTree(Easy) │ ├── README.md │ └── mergeTwoBinaryTree.py ├── 7. regularExpressionMatching(Hard) │ ├── README.md │ └── regularExpressionMatching.py ├── 8. addTwoLinkedNumbers(Medium) │ ├── README.md │ └── addTwoNumbers.py └── 9. twoSum(Easy) │ ├── README.md │ └── twoSum.py ├── 10-19 ├── 10. reverseInteger(Easy) │ ├── README.md │ └── reverseInteger.py ├── 11. Container With Most Water(Medium) │ ├── README.md │ └── containerWithMostWater.py ├── 12. Integer to Roman(Medium) │ ├── README.md │ └── integerToRoman.py ├── 13. Roman to integer(Easy) │ ├── README.md │ └── romanToInt.py ├── 14. Longest Common Prefix(Easy) │ ├── README.md │ └── longestCommonPrefix.py ├── 15. 3Sum(Medium) │ ├── 3Sum.py │ └── README.md ├── 16. 3SumClosest(Medium) │ ├── 3SumClosest.py │ └── README.md ├── 17. Letter Combinations of a Phone Number(Medium) │ ├── README.md │ ├── img │ │ └── Telephone.svg.png │ └── letterCombinations.py ├── 18. 4Sum(Medium) │ ├── 4Sum.py │ └── README.md └── 19. Remove Nth Node From End of List(Medium) │ ├── README.md │ └── removeNthFromEnd.py ├── 20-29 ├── .DS_Store ├── 20. Valid Parentheses(Easy) │ ├── README.md │ └── Valid Parentheses.py ├── 21. Merge Two Sorted Lists(Easy) │ ├── README.md │ └── mergeTwoLists.py ├── 22. Generate Parentheses(Medium) │ ├── Generate Parentheses.py │ └── README.md ├── 23. Merge k Sorted Lists(Hard) │ ├── Merge k Sorted Lists.py │ └── README.md ├── 24. Swap Nodes in Pairs(Medium) │ ├── README.md │ └── Swap Nodes in Pairs.py ├── 25. Reverse Nodes in k-Group(Hard) │ ├── README.md │ └── Reverse Nodes in k-Group.py ├── 26. Remove Duplicates from Sorted Array(Easy) │ ├── README.md │ └── Remove Duplicates from Sorted Array.py ├── 27. Divide Two Integers(Hard) │ ├── Divide Two Integers.py │ └── README.md ├── 28. Substring with Concatenation of All Words(Hard) │ ├── .DS_Store │ ├── README.md │ └── Substring with Concatenation of All Words.py └── 29. Next Permutation(Medium) │ ├── Next Permutation.py │ └── README.md ├── 30-39 ├── 30. Longest Valid Parentheses(Hard) │ ├── Longest Valid Parentheses.py │ └── README.md ├── 31. Search in Rotated Sorted Array(Medium) │ ├── README.md │ └── Search in Rotated Sorted Array.py ├── 32. Search for a Range(Medium) │ ├── README.md │ └── Search for a Range.py ├── 33. Search Insert Position(Easy) │ ├── README.md │ └── Search Insert Position.py ├── 34. Valid Sudoku(Medium) │ ├── README.md │ └── Valid Sudoku.py ├── 35. Sudoku Solver(Hard) │ ├── README.md │ └── Sudoku Solver.py ├── 36. Count and Say(Easy) │ ├── Count and Say.py │ └── README.md ├── 37. Combination Sum(Medium) │ ├── Combination Sum.py │ └── README.md ├── 38. Combination Sum II(Medium) │ ├── Combination Sum II.py │ └── README.md └── 39. First Missing Positive(Hard) │ ├── First Missing Positive.py │ └── README.md ├── 40-49 ├── 40. Trapping Rain Water(Hard) │ ├── README.md │ ├── Trapping Rain Water.py │ └── rainwatertrap.png ├── 41. Multiply Strings(Medium) │ ├── Multiply Strings.py │ └── README.md ├── 42. Jump Game II(Hard) │ ├── README.md │ └── jump_game_II.cpp ├── 43. Jump Game I(Medium) │ ├── README.md │ └── jump_game_I.cpp ├── 44. Maximum Subarray(Easy) │ ├── Maximum Subarray.cpp │ └── README.md ├── 45. Rotate Image(Medium) │ ├── README.md │ └── Rotate Image.cpp ├── 46. Spiral Matrix(Medium) │ ├── README.md │ └── Spiral Matrix.cpp ├── 47. Merge Intervals(Medium) │ ├── Merge Intervals.cpp │ └── README.md ├── 48. Insert Interval(Hard) │ ├── Insert Interval.cpp │ └── README.md └── 49. Spiral Matrix II(Medium) │ ├── README.md │ └── Spiral Matrix II.cpp ├── 50-59 ├── 50. Unique Paths(Medium) │ ├── README.md │ ├── Unique Paths.cpp │ └── robot_maze.png ├── 51. Unique Paths II(Medium) │ ├── README.md │ ├── Unique Paths II.cpp │ └── robot_maze.png ├── 52. Minimum Path Sum(Medium) │ ├── Minimum Path Sum.cpp │ └── README.md ├── 53. Plus One(Easy) │ ├── Plus One.cpp │ └── README.md ├── 54. Set Matrix Zeros(Medium) │ ├── README.md │ └── Set Matrix Zeroes.cpp ├── 55. Search a 2D Matrix(Medium) │ ├── README.md │ └── Search a 2D Matrix.cpp ├── 56. Sort Colors(Medium) │ ├── README.md │ └── Sort Colors.cpp ├── 57. Subsets(Medium) │ ├── README.md │ └── Subsets.cpp ├── 58. Word Search(Medium) │ ├── README.md │ └── Word Search.cpp └── 59. Remove Duplicates from Sorted Array II(Medium) │ ├── README.md │ └── Remove Duplicates from Sorted Array II.cpp ├── 60-69 ├── 60. Linked List Cycle(Easy) │ ├── 141.linked-list-cycle.cpp │ ├── README.md │ ├── circularlinkedlist.png │ ├── circularlinkedlist_test2.png │ └── circularlinkedlist_test3.png ├── 61. Linked List Cycle II(Medium) │ ├── 142.linked-list-cycle-ii.cpp │ ├── 2.jpeg │ ├── README.md │ ├── circularlinkedlist.png │ ├── circularlinkedlist_test2.png │ └── circularlinkedlist_test3.png ├── 62. Intersection of Two Linked Lists(Easy) │ ├── 160.intersection-of-two-linked-lists.cpp │ ├── 160_example_1.png │ ├── 160_example_2.png │ ├── 160_example_3.png │ ├── 160_statement.png │ ├── 2.jpeg │ └── README.md ├── 63. Middle of the Linked List(Easy) │ ├── 876.middle-of-the-linked-list.cpp │ ├── README.md │ ├── lc-midlist1.jpg │ └── lc-midlist2.jpg ├── 64. Reverse Linked List II(Medium) │ ├── 92.reverse-linked-list-ii.cpp │ ├── README.md │ └── rev2ex2.jpg ├── 65. Remove Duplicates from Sorted List(Easy) │ ├── 83.remove-duplicates-from-sorted-list.cpp │ ├── README.md │ ├── list1.jpeg │ └── list2.jpeg ├── 66. Partition List(Medium) │ ├── 86.partition-list.cpp │ ├── README.md │ └── partition.jpg └── 67. Copy List with Random Pointer(Medium) │ ├── 138.copy-list-with-random-pointer.cpp │ ├── README.md │ ├── e1.png │ ├── e2.png │ └── e3.png ├── BFS ├── 102.二叉树的层序遍历.cpp ├── 107.二叉树的层序遍历-ii.cpp ├── 111.minimum-depth-of-binary-tree.cpp ├── 113.路径总和-ii.cpp ├── 117.填充每个节点的下一个右侧节点指针-ii.cpp ├── 129.求根节点到叶节点数字之和.cpp ├── 130.被围绕的区域.cpp ├── 133.克隆图.cpp ├── 199.二叉树的右视图.cpp ├── 279.完全平方数.cpp ├── 752.open-the-lock.cpp ├── 773.sliding-puzzle.cpp ├── 884.两句话中的不常见单词.cpp └── 933.最近的请求次数.cpp ├── DFS ├── 100.相同的树.cpp ├── 101.对称二叉树.cpp ├── 1022.从根到叶的二进制数之和.cpp ├── 1030.距离顺序排列矩阵单元格.cpp ├── 104.二叉树的最大深度.cpp ├── 108.将有序数组转换为二叉搜索树.cpp ├── 110.平衡二叉树.cpp ├── 112.路径总和.cpp ├── 129.求根节点到叶节点数字之和.cpp ├── 257.二叉树的所有路径.cpp ├── 733.图像渲染.cpp ├── 744.寻找比目标字母大的最小字母.cpp ├── 766.托普利茨矩阵.cpp ├── 922.按奇偶排序数组-ii.cpp └── 999.可以被一步捕获的棋子数.cpp ├── README.md ├── 二分查找 ├── 153.寻找旋转排序数组中的最小值.cpp ├── 162.寻找峰值.cpp ├── 240.搜索二维矩阵-ii.cpp ├── 275.h-指数-ii.cpp ├── 278.第一个错误的版本.cpp ├── 367.有效的完全平方数.cpp ├── 374.猜数字大小.cpp ├── 436.寻找右区间.cpp ├── 441.排列硬币.cpp ├── 69.x-的平方根.cpp ├── 786.第-k-个最小的素数分数.cpp ├── 910.最小差值-ii.cpp └── 912.排序数组.cpp ├── 二叉搜索树 ├── 1038.binary-search-tree-to-greater-sum-tree.cpp ├── 230.kth-smallest-element-in-a-bst.cpp ├── 450.delete-node-in-a-bst.cpp ├── 538.convert-bst-to-greater-tree.cpp ├── 653.两数之和-iv-输入-bst.cpp ├── 700.search-in-a-binary-search-tree.cpp ├── 701.insert-into-a-binary-search-tree.cpp ├── 95.不同的二叉搜索树-ii.cpp ├── 96.unique-binary-search-trees.cpp ├── 98.validate-binary-search-tree.cpp └── 99.恢复二叉搜索树.cpp ├── 二叉树 ├── 103.binary-tree-zigzag-level-order-traversal.cpp ├── 105.construct-binary-tree-from-preorder-and-inorder-traversal.cpp ├── 106.construct-binary-tree-from-inorder-and-postorder-traversal.cpp ├── 109.convert-sorted-list-to-binary-search-tree.cpp ├── 116.populating-next-right-pointers-in-each-node.cpp ├── 124.binary-tree-maximum-path-sum.cpp ├── 144.二叉树的前序遍历.cpp ├── 145.二叉树的后序遍历.cpp ├── 222.count-complete-tree-nodes.cpp ├── 226.invert-binary-tree.cpp ├── 236.lowest-common-ancestor-of-a-binary-tree.cpp ├── 297.serialize-and-deserialize-binary-tree.cpp ├── 543.diameter-of-binary-tree.cpp ├── 652.find-duplicate-subtrees.cpp └── 654.maximum-binary-tree.cpp ├── 动态规划 ├── 1143.longest-common-subsequence.cpp ├── 120.triangle.cpp ├── 139.单词拆分.cpp ├── 151.reverse-words-in-a-string.cpp ├── 198.house-robber.cpp ├── 213.house-robber-ii.cpp ├── 300.longest-increasing-subsequence.cpp ├── 322.coin-change.cpp ├── 337.house-robber-iii.cpp ├── 354.russian-doll-envelopes.cpp ├── 416.partition-equal-subset-sum.cpp ├── 44.通配符匹配.cpp ├── 450.delete-node-in-a-bst.cpp ├── 494.target-sum.cpp ├── 509.fibonacci-number.cpp ├── 516.longest-palindromic-subsequence.cpp ├── 518.coin-change-2.cpp ├── 518.零钱兑换-ii.cpp ├── 53.maximum-subarray.cpp ├── 583.delete-operation-for-two-strings.cpp ├── 712.minimum-ascii-delete-sum-for-two-strings.cpp ├── 72.edit-distance.cpp ├── 887.super-egg-drop.cpp ├── 91.decode-ways.cpp ├── 91.decode-ways.py └── 931.minimum-falling-path-sum.cpp ├── 单调栈 ├── 496.下一个更大元素-i.cpp ├── 503.下一个更大元素-ii.cpp └── 739.每日温度.cpp ├── 双指针 ├── 1089.复写零.cpp ├── 125.验证回文串.cpp ├── 1332.删除回文子序列.cpp ├── 1385.两个数组间的距离值.cpp ├── 189.轮转数组.cpp ├── 209.长度最小的子数组.cpp ├── 283.移动零.cpp ├── 287.寻找重复数.cpp ├── 331.验证二叉树的前序序列化.cpp ├── 344.反转字符串.cpp ├── 345.反转字符串中的元音字母.cpp ├── 350.两个数组的交集-ii.cpp ├── 392.判断子序列.cpp ├── 475.供暖器.cpp ├── 524.通过删除字母匹配到字典里最长单词.cpp ├── 532.数组中的-k-diff-数对.cpp ├── 541.reverse-string-ii.cpp ├── 557.reverse-words-in-a-string-iii.cpp ├── 567.permutation-in-string.cpp ├── 581.最短无序连续子数组.cpp ├── 611.有效三角形的个数.cpp ├── 633.平方数之和.cpp ├── 658.找到-k-个最接近的元素.cpp ├── 696.计数二进制子串.cpp ├── 763.划分字母区间.cpp ├── 795.区间子数组个数.cpp ├── 821.字符的最短距离.cpp ├── 825.适龄的朋友.cpp ├── 826.安排工作以达到最大收益.cpp ├── 832.翻转图像.cpp ├── 844.比较含退格的字符串.cpp ├── 922.按奇偶排序数组-ii.cpp ├── 925.长按键入.cpp └── 977.有序数组的平方.cpp ├── 哈希表 ├── 169.多数元素.cpp ├── 187.重复的dna序列.cpp ├── 202.快乐数.cpp ├── 204.计数质数.cpp ├── 205.同构字符串.cpp ├── 217.存在重复元素.cpp ├── 219.存在重复元素-ii.cpp ├── 242.有效的字母异位词.cpp ├── 274.h-指数.cpp ├── 290.单词规律.cpp ├── 299.猜数字游戏.cpp ├── 347.前-k-个高频元素.cpp ├── 349.两个数组的交集.cpp ├── 383.赎金信.cpp ├── 387.字符串中的第一个唯一字符.cpp ├── 389.找不同.cpp ├── 409.最长回文串.cpp ├── 438.找到字符串中所有字母异位词.cpp ├── 451.根据字符出现频率排序.cpp ├── 454.四数相加-ii.cpp ├── 49.字母异位词分组.cpp ├── 500.键盘行.cpp ├── 508.出现次数最多的子树元素和.cpp ├── 525.连续数组.cpp ├── 554.砖墙.cpp ├── 575.分糖果.cpp ├── 594.最长和谐子序列.cpp └── 599.两个列表的最小索引总和.cpp ├── 回溯法 ├── 15.3-sum.cpp ├── 1541.minimum-insertions-to-balance-a-parentheses-string.cpp ├── 20.valid-parentheses.cpp ├── 22.generate-parentheses.cpp ├── 37.sudoku-solver.cpp ├── 39.combination-sum.cpp ├── 46.permutations.cpp ├── 47.全排列-ii.cpp ├── 51.n-queens.cpp ├── 52.n皇后-ii.cpp ├── 77.combinations.cpp ├── 78.subsets.cpp └── 921.minimum-add-to-make-parentheses-valid.cpp ├── 图论 ├── 1254.number-of-closed-islands.cpp ├── 200.number-of-islands.cpp ├── 207.course-schedule.cpp ├── 210.course-schedule-ii.cpp └── 797.all-paths-from-source-to-target.cpp ├── 字符串 ├── .vscode │ ├── c_cpp_properties.json │ ├── launch.json │ └── settings.json ├── 1234.替换子串得到平衡字符串.cpp ├── 43.multiply-strings.cpp ├── 49.字母异位词分组.cpp ├── 58.length-of-last-word.cpp ├── 6.zigzag-conversion.cpp ├── 67.add-binary.cpp ├── 93.复原-ip-地址.cpp └── 97.交错字符串.cpp ├── 已整理 ├── 138.copy-list-with-random-pointer.cpp ├── 141.linked-list-cycle.cpp ├── 142.linked-list-cycle-ii.cpp ├── 3.longest-substring-without-repeating-characters.cpp ├── 5.longest-palindromic-substring.cpp ├── 86.partition-list.cpp └── 92.reverse-linked-list-ii.cpp ├── 数学运算技巧 ├── 1201.丑数-iii.cpp ├── 136.single-number.cpp ├── 137.只出现一次的数字-ii.cpp ├── 168.excel-表列名称.cpp ├── 171.excel-表列序号.cpp ├── 172.factorial-trailing-zeroes.cpp ├── 191.number-of-1-bits.cpp ├── 231.power-of-two.cpp ├── 263.丑数.cpp ├── 264.丑数-ii.cpp ├── 313.超级丑数.cpp ├── 50.pow-x-n.cpp └── 89.格雷编码.cpp ├── 数组 ├── 1.two-sum.cpp ├── 1011.capacity-to-ship-packages-within-d-days.cpp ├── 1081.smallest-subsequence-of-distinct-characters.cpp ├── 1094.car-pooling.cpp ├── 1109.corporate-flight-bookings.cpp ├── 118.pascals-triangle.cpp ├── 119.pascals-triangle-ii.cpp ├── 120.triangle.cpp ├── 128.最长连续序列.cpp ├── 15.3-sum.cpp ├── 152.乘积最大子数组.cpp ├── 167.two-sum-ii-input-array-is-sorted.cpp ├── 228.汇总区间.cpp ├── 27.remove-element.cpp ├── 303.range-sum-query-immutable.cpp ├── 304.range-sum-query-2-d-immutable.cpp ├── 316.remove-duplicate-letters.cpp ├── 32.longest-valid-parentheses.cpp ├── 34.find-first-and-last-position-of-element-in-sorted-array.cpp ├── 410.split-array-largest-sum.cpp ├── 48.rotate-image.cpp ├── 53.maximum-subarray.cpp ├── 560.subarray-sum-equals-k.cpp ├── 704.binary-search.cpp ├── 76.minimum-window-substring.cpp ├── 85.maximal-rectangle.cpp ├── 85.最大矩形.cpp ├── 870.advantage-shuffle.cpp ├── 875.koko-eating-bananas.cpp ├── 887.super-egg-drop.cpp └── 90.subsets-ii.cpp ├── 栈 ├── 1078.bigram-分词.cpp ├── 1128.等价多米诺骨牌对的数量.cpp ├── 150.逆波兰表达式求值.cpp ├── 155.最小栈.cpp ├── 225.用队列实现栈.cpp ├── 232.用栈实现队列.cpp ├── 341.扁平化嵌套列表迭代器.cpp ├── 456.132-模式.cpp ├── 682.棒球比赛.cpp ├── 71.简化路径.cpp ├── 781.森林中的兔子.cpp └── 94.二叉树的中序遍历.cpp ├── 股票买卖问题 ├── 121.best-time-to-buy-and-sell-stock.cpp ├── 122.best-time-to-buy-and-sell-stock-ii.cpp ├── 123.best-time-to-buy-and-sell-stock-iii.cpp ├── 188.best-time-to-buy-and-sell-stock-iv.cpp ├── 309.best-time-to-buy-and-sell-stock-with-cooldown.cpp └── 714.best-time-to-buy-and-sell-stock-with-transaction-fee.cpp ├── 设计数据结构 ├── 146.lru-cache.cpp ├── 155.最小栈.cpp ├── 234.palindrome-linked-list.cpp ├── 295.find-median-from-data-stream.cpp ├── 355.design-twitter.cpp ├── 380.insert-delete-get-random-o-1.cpp ├── 382.linked-list-random-node.cpp ├── 460.lfu-cache.cpp ├── 710.random-pick-with-blacklist.cpp └── 895.maximum-frequency-stack.cpp ├── 贪心算法 ├── 1005.k-次取反后最大化的数组和.cpp ├── 1024.video-stitching.cpp ├── 1288.remove-covered-intervals.cpp ├── 134.gas-station.cpp ├── 135.分发糖果.cpp ├── 376.摆动序列.cpp ├── 406.根据身高重建队列.cpp ├── 435.non-overlapping-intervals.cpp ├── 452.minimum-number-of-arrows-to-burst-balloons.cpp ├── 455.分发饼干.cpp ├── 860.柠檬水找零.cpp └── 986.interval-list-intersections.cpp ├── 链表 ├── 1019.链表中的下一个更大节点.cpp ├── 109.有序链表转换二叉搜索树.cpp ├── 114.cpp ├── 114.flatten-binary-tree-to-linked-list.cpp ├── 1171.从链表中删去总和值为零的连续节点.cpp ├── 1290.二进制链表转整数.cpp ├── 143.重排链表.cpp ├── 147.对链表进行插入排序.cpp ├── 148.排序链表.cpp ├── 160.intersection-of-two-linked-lists.cpp ├── 1669.合并两个链表.cpp ├── 1670.设计前中后队列.cpp ├── 1721.交换链表中的节点.cpp ├── 203.移除链表元素.cpp ├── 206.reverse-linked-list.cpp ├── 2130.链表最大孪生和.cpp ├── 215.kth-largest-element-in-an-array.cpp ├── 2181.合并零之间的节点.cpp ├── 23.merge-k-sorted-lists.cpp ├── 237.删除链表中的节点.cpp ├── 25.reverse-nodes-in-k-group.cpp ├── 328.奇偶链表.cpp ├── 445.两数相加-ii.cpp ├── 61.rotate-list.cpp ├── 725.分隔链表.cpp ├── 817.链表组件.cpp ├── 82.remove-duplicates-from-sorted-list-ii.cpp ├── 82.删除排序链表中的重复元素-ii.cpp ├── 876.middle-of-the-linked-list.cpp ├── 876.链表的中间结点.cpp └── 92.reverse-linked-list-ii.cpp └── 高频面试题 ├── 11.container-with-most-water.cpp ├── 224.basic-calculator.cpp ├── 227.basic-calculator-ii.cpp ├── 391.perfect-rectangle.cpp ├── 42.trapping-rain-water.cpp ├── 43.multiply-strings.cpp ├── 659.split-array-into-consecutive-subsequences.cpp ├── 855.exam-room.cpp └── 969.pancake-sorting.cpp /1-9/3. longestSubstringWithoutRepeating(Medium)/lengthOfLongestSubstring.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string, find the length of the longest substring without repeating characters. 3 | 4 | Examples: 5 | 6 | Given "abcabcbb", the answer is "abc", which the length is 3. 7 | 8 | Given "bbbbb", the answer is "b", with the length of 1. 9 | 10 | Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. 11 | ''' 12 | class Solution(object): 13 | # @return an integer 14 | def lengthOfLongestSubstring(self, s): 15 | start = maxLength = 0 16 | usedChar = {} 17 | 18 | for i in range(len(s)): 19 | if s[i] in usedChar and start <= usedChar[s[i]]: 20 | start = usedChar[s[i]] + 1 21 | else: 22 | maxLength = max(maxLength, i - start + 1) 23 | usedChar[s[i]] = i 24 | 25 | return maxLength 26 | 27 | a = Solution().lengthOfLongestSubstring('asdapubdlic') 28 | print(a) -------------------------------------------------------------------------------- /1-9/5. palindromeNumber(Easy)/isNumberPalindrome.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Determine whether an integer is a palindrome. Do this without extra space. 3 | ''' 4 | 5 | class Solution(object): 6 | def isPalindrome(self, x): 7 | """ 8 | :type x: int 9 | :rtype: bool 10 | """ 11 | if x < 0: 12 | return False 13 | 14 | if len(str(x)) % 2 == 0: 15 | return int(str(x)[:len(str(x))//2]) == int(str(x)[len(str(x))//2:][::-1]) 16 | else: 17 | return int(str(x)[:len(str(x))//2+1]) == int(str(x)[len(str(x))//2:][::-1]) 18 | 19 | 20 | a = Solution().isPalindrome(+2147447412) 21 | print(a) 22 | -------------------------------------------------------------------------------- /10-19/10. reverseInteger(Easy)/README.md: -------------------------------------------------------------------------------- 1 | # 反转整数 2 | #### *Reverse Integer* 3 | 4 | **example 1** 5 | ``` 6 | input: x = 123, return 321 7 | ``` 8 | **example 2** 9 | ``` 10 | input: x = -123, return -321 11 | ``` 12 | note: 13 | * The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows. 14 | ### 思路 15 | 1. 简单到不用说思路,只需要注意在python里int的存储整数是没有最大值上限的,于是为了AC,我们只好画蛇添足般加了if判断 16 | 2. 32位整数存储范围是`-2147483648`到`2147483647` 17 | 18 | 19 | ### 代码 20 | ``` 21 | class Solution(object): 22 | def reverse(self, x): 23 | """ 24 | :type x: int 25 | :rtype: int 26 | """ 27 | sx = str(x) 28 | if sx[0] == '-': 29 | sx = '-' + sx[-1:0:-1] 30 | else: 31 | sx = sx[::-1] 32 | ret = int(sx) 33 | if ret > 2147483647 or ret < -2147483648: 34 | return 0 35 | else: 36 | return ret 37 | ``` -------------------------------------------------------------------------------- /10-19/13. Roman to integer(Easy)/README.md: -------------------------------------------------------------------------------- 1 | # 罗马数字转换成阿拉伯数字 2 | #### *Roman to integer* 3 | 4 | * Given a roman numeral, convert it to an integer. 5 | 6 | * Input is guaranteed to be within the range from 1 to 3999. 7 | 8 | **example 1** 9 | ``` 10 | input: CCCLXXXIX 11 | output: 389 12 | 13 | ``` 14 | 15 | ### 思路 16 | 1. dict存储单个罗马字母代表的阿拉伯数字 17 | 2. 初始状态`sum = 0`,循环遍历字符串,如果 `s[i]`所代表的阿拉伯数字大于`s[i+1]`的,则加到`sum`上,如果小于,则`sum`减去`s[i]`代表的阿拉伯数字 18 | 19 | 20 | 21 | ### 代码 22 | ``` 23 | class Solution(object): 24 | def romanToInt(self, s): 25 | """ 26 | :type s: str 27 | :rtype: int 28 | """ 29 | a = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1} 30 | sum = 0 31 | for i in range(len(s) - 1): #range右边界len(s) - 1 保证 i + 1不会下标越界 32 | if a[s[i]] < a[s[i+1]]: 33 | sum -= a[s[i]] 34 | else: 35 | sum += a[s[i]] 36 | return sum + a[s[len(s) - 1]] 37 | ``` -------------------------------------------------------------------------------- /10-19/13. Roman to integer(Easy)/romanToInt.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Time : 2017/6/23 上午11:00 3 | # @Author : fj 4 | # @Site : 5 | # @File : romanToInt.py 6 | # @Software: PyCharm 7 | 8 | # * Given a roman numeral, convert it to an integer. 9 | # 10 | # * Input is guaranteed to be within the range from 1 to 3999. 11 | 12 | class Solution(object): 13 | def romanToInt(self, s): 14 | """ 15 | :type s: str 16 | :rtype: int 17 | """ 18 | a = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1} 19 | sum = 0 20 | for i in range(len(s) - 1): #range右边界len(s) - 1 保证 i + 1不会下标越界 21 | if a[s[i]] < a[s[i+1]]: 22 | sum -= a[s[i]] 23 | else: 24 | sum += a[s[i]] 25 | return sum + a[s[len(s) - 1]] 26 | 27 | a = Solution().romanToInt('CCCLXXXIX') 28 | print(a) -------------------------------------------------------------------------------- /10-19/17. Letter Combinations of a Phone Number(Medium)/img/Telephone.svg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/10-19/17. Letter Combinations of a Phone Number(Medium)/img/Telephone.svg.png -------------------------------------------------------------------------------- /20-29/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/20-29/.DS_Store -------------------------------------------------------------------------------- /20-29/20. Valid Parentheses(Easy)/Valid Parentheses.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Time : 2017/6/30 上午10:39 3 | # @Author : fj 4 | # @Site : 5 | # @File : Valid Parentheses.py 6 | # @Software: PyCharm 7 | 8 | # Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 9 | # 10 | # The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. 11 | 12 | class Solution(object): 13 | def isValid(self, s): 14 | """ 15 | :type s: str 16 | :rtype: bool 17 | """ 18 | brackets = { 19 | '(': ')', 20 | '[': ']', 21 | '{': '}' 22 | } 23 | stack = [] 24 | for i in s: 25 | if i in brackets: 26 | stack.append(brackets[i]) 27 | elif i in brackets.values(): 28 | if len(stack) == 0 or stack.pop(-1) != i: 29 | return False 30 | return len(stack) == 0 31 | 32 | a = Solution().isValid('') 33 | print(a) -------------------------------------------------------------------------------- /20-29/24. Swap Nodes in Pairs(Medium)/Swap Nodes in Pairs.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Time : 2017/7/20 上午10:55 3 | # @Author : fj 4 | # @Site : 5 | # @File : Swap Nodes in Pairs.py 6 | # @Software: PyCharm 7 | 8 | # Given a linked list, swap every two adjacent nodes and return its head. 9 | # 10 | # For example, 11 | # Given 1->2->3->4, you should return the list as 2->1->4->3. 12 | # 13 | # Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. 14 | 15 | 16 | # Definition for singly-linked list. 17 | class ListNode(object): 18 | def __init__(self, x): 19 | self.val = x 20 | self.next = None 21 | 22 | class Solution(object): 23 | def swapPairs(self, head): 24 | """ 25 | :type head: ListNode 26 | :rtype: ListNode 27 | """ 28 | try: 29 | prev = head 30 | tail = prev.next 31 | while True: 32 | prev.val, tail.val = tail.val, prev.val 33 | prev = tail.next 34 | tail = prev.next 35 | finally: 36 | return head -------------------------------------------------------------------------------- /20-29/26. Remove Duplicates from Sorted Array(Easy)/Remove Duplicates from Sorted Array.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Time : 2017/7/31 下午6:05 3 | # @Author : fj 4 | # @Site : 5 | # @File : Remove Duplicates from Sorted Array.py 6 | # @Software: PyCharm 7 | 8 | 9 | # Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. 10 | # 11 | # Do not allocate extra space for another array, you must do this in place with constant memory. 12 | # 13 | # For example, 14 | # Given input array nums = [1,1,2], 15 | # 16 | # Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. 17 | # It doesn't matter what you leave beyond the new length. 18 | 19 | class Solution(object): 20 | def removeDuplicates(self, nums): 21 | """ 22 | :type nums: List[int] 23 | :rtype: int 24 | """ 25 | idx = 0 26 | for i in range(len(nums)): 27 | if nums[idx] != nums[i]: 28 | idx += 1 29 | nums[idx] = nums[i] 30 | return idx + 1 31 | 32 | 33 | 34 | 35 | a = Solution().removeDuplicates([]) 36 | print(a) 37 | -------------------------------------------------------------------------------- /20-29/27. Divide Two Integers(Hard)/Divide Two Integers.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # @Time : 2017/8/1 下午5:23 3 | # @Author : fj 4 | # @Site : 5 | # @File : Divide Two Integers.py 6 | # @Software: PyCharm 7 | 8 | # Divide two integers without using multiplication, division and mod operator. 9 | # 10 | # If it is overflow, return MAX_INT. 11 | 12 | class Solution(object): 13 | def divide(self, dividend, divisor): 14 | """ 15 | :type dividend: int 16 | :type divisor: int 17 | :rtype: int 18 | """ 19 | pos = (dividend < 0) is (divisor < 0) 20 | dividend, divisor = abs(dividend), abs(divisor) 21 | result = 0 22 | while dividend >= divisor: 23 | tmp, i = divisor, 1 24 | while dividend - tmp >= 0: 25 | dividend -= tmp 26 | result += i 27 | i <<= 1 28 | tmp <<= 1 29 | if not pos: 30 | result = -result 31 | return min(2147483647, max(result, -2147483648)) 32 | 33 | a = Solution().divide(1, 2) 34 | print(a) 35 | -------------------------------------------------------------------------------- /20-29/28. Substring with Concatenation of All Words(Hard)/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/20-29/28. Substring with Concatenation of All Words(Hard)/.DS_Store -------------------------------------------------------------------------------- /40-49/40. Trapping Rain Water(Hard)/rainwatertrap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/40-49/40. Trapping Rain Water(Hard)/rainwatertrap.png -------------------------------------------------------------------------------- /40-49/41. Multiply Strings(Medium)/Multiply Strings.py: -------------------------------------------------------------------------------- 1 | ''' 2 | /* 3 | * @Author: Fengjie 4 | * @Date: 2018-05-08 16:54:27 5 | * @Last Modified by: Fengjie 6 | * @Last Modified time: 2018-05-08 16:54:27 7 | */ 8 | ''' 9 | class Solution: 10 | def multiply(self, num1, num2): 11 | """ 12 | :type num1: str 13 | :type num2: str 14 | :rtype: str 15 | """ 16 | num1_int = 0 17 | num2_int = 0 18 | for i in range(len(num1)): 19 | num1_int += (ord(num1[i]) - 48) * 10**(len(num1) -i -1) 20 | for i in range(len(num2)): 21 | num2_int += (ord(num2[i]) - 48) * 10**(len(num2) -i -1) 22 | result_int = num1_int * num2_int 23 | result_str = '' 24 | while result_int > 0: 25 | ascode = result_int % 10 26 | result_str = chr(ascode + 48) + result_str 27 | result_int = result_int // 10 28 | return result_str if result_str else '0' 29 | 30 | a = Solution().multiply('123', '') 31 | print(a) -------------------------------------------------------------------------------- /40-49/43. Jump Game I(Medium)/jump_game_I.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | bool canJump(vector& nums) { 8 | #define MAX(a, b) ((a) > (b) ? (a): (b)) 9 | int farthest = 0; 10 | int next = nums[0]; 11 | for (int i =0; i < nums.size() - 1; ++i) 12 | { 13 | farthest = MAX(farthest, i + nums[i]); 14 | if (farthest >= nums.size()) 15 | return true; 16 | if (i == next) 17 | { 18 | next = farthest; 19 | if (next == i) 20 | return false; 21 | } 22 | } 23 | return true; 24 | } 25 | }; 26 | 27 | int main(int argc, char* argv) 28 | { 29 | vector nums1 = { 3,2,1,0,4 }; //false 30 | vector nums2 = { 2,3,1,1,4 }; //true 31 | cout << Solution().canJump(nums1) << endl; 32 | return 0; 33 | } -------------------------------------------------------------------------------- /40-49/44. Maximum Subarray(Easy)/Maximum Subarray.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/40-49/44. Maximum Subarray(Easy)/Maximum Subarray.cpp -------------------------------------------------------------------------------- /40-49/46. Spiral Matrix(Medium)/Spiral Matrix.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/40-49/46. Spiral Matrix(Medium)/Spiral Matrix.cpp -------------------------------------------------------------------------------- /40-49/47. Merge Intervals(Medium)/Merge Intervals.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/40-49/47. Merge Intervals(Medium)/Merge Intervals.cpp -------------------------------------------------------------------------------- /40-49/48. Insert Interval(Hard)/Insert Interval.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/40-49/48. Insert Interval(Hard)/Insert Interval.cpp -------------------------------------------------------------------------------- /40-49/49. Spiral Matrix II(Medium)/Spiral Matrix II.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/40-49/49. Spiral Matrix II(Medium)/Spiral Matrix II.cpp -------------------------------------------------------------------------------- /50-59/50. Unique Paths(Medium)/Unique Paths.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/50-59/50. Unique Paths(Medium)/Unique Paths.cpp -------------------------------------------------------------------------------- /50-59/50. Unique Paths(Medium)/robot_maze.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/50-59/50. Unique Paths(Medium)/robot_maze.png -------------------------------------------------------------------------------- /50-59/51. Unique Paths II(Medium)/Unique Paths II.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/50-59/51. Unique Paths II(Medium)/Unique Paths II.cpp -------------------------------------------------------------------------------- /50-59/51. Unique Paths II(Medium)/robot_maze.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/50-59/51. Unique Paths II(Medium)/robot_maze.png -------------------------------------------------------------------------------- /50-59/52. Minimum Path Sum(Medium)/Minimum Path Sum.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/50-59/52. Minimum Path Sum(Medium)/Minimum Path Sum.cpp -------------------------------------------------------------------------------- /50-59/53. Plus One(Easy)/Plus One.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/50-59/53. Plus One(Easy)/Plus One.cpp -------------------------------------------------------------------------------- /50-59/55. Search a 2D Matrix(Medium)/Search a 2D Matrix.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/50-59/55. Search a 2D Matrix(Medium)/Search a 2D Matrix.cpp -------------------------------------------------------------------------------- /50-59/58. Word Search(Medium)/Word Search.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/50-59/58. Word Search(Medium)/Word Search.cpp -------------------------------------------------------------------------------- /60-69/60. Linked List Cycle(Easy)/141.linked-list-cycle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=141 lang=cpp 3 | * 4 | * [141] Linked List Cycle 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for singly-linked list. 10 | * struct ListNode { 11 | * int val; 12 | * ListNode *next; 13 | * ListNode(int x) : val(x), next(NULL) {} 14 | * }; 15 | */ 16 | class Solution { 17 | public: 18 | bool hasCycle(ListNode *head) { 19 | if (head == nullptr) 20 | return false; 21 | ListNode *p1, *p2; 22 | p1 = p2 = head; 23 | while (p2->next != nullptr && p2->next->next != nullptr) 24 | { 25 | p2 = p2->next->next; 26 | p1 = p1->next; 27 | if (p2 == p1) 28 | return true; 29 | } 30 | return false; 31 | } 32 | }; 33 | // @lc code=end 34 | 35 | -------------------------------------------------------------------------------- /60-69/60. Linked List Cycle(Easy)/circularlinkedlist.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/60-69/60. Linked List Cycle(Easy)/circularlinkedlist.png -------------------------------------------------------------------------------- /60-69/60. Linked List Cycle(Easy)/circularlinkedlist_test2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/60-69/60. Linked List Cycle(Easy)/circularlinkedlist_test2.png -------------------------------------------------------------------------------- /60-69/60. Linked List Cycle(Easy)/circularlinkedlist_test3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/60-69/60. Linked List Cycle(Easy)/circularlinkedlist_test3.png -------------------------------------------------------------------------------- /60-69/61. Linked List Cycle II(Medium)/2.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/60-69/61. Linked List Cycle II(Medium)/2.jpeg -------------------------------------------------------------------------------- /60-69/61. Linked List Cycle II(Medium)/circularlinkedlist.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/60-69/61. Linked List Cycle II(Medium)/circularlinkedlist.png -------------------------------------------------------------------------------- /60-69/61. Linked List Cycle II(Medium)/circularlinkedlist_test2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/60-69/61. Linked List Cycle II(Medium)/circularlinkedlist_test2.png -------------------------------------------------------------------------------- /60-69/61. Linked List Cycle II(Medium)/circularlinkedlist_test3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/60-69/61. Linked List Cycle II(Medium)/circularlinkedlist_test3.png -------------------------------------------------------------------------------- /60-69/62. Intersection of Two Linked Lists(Easy)/160_example_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/60-69/62. Intersection of Two Linked Lists(Easy)/160_example_1.png -------------------------------------------------------------------------------- /60-69/62. Intersection of Two Linked Lists(Easy)/160_example_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/60-69/62. Intersection of Two Linked Lists(Easy)/160_example_2.png -------------------------------------------------------------------------------- /60-69/62. Intersection of Two Linked Lists(Easy)/160_example_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/60-69/62. Intersection of Two Linked Lists(Easy)/160_example_3.png -------------------------------------------------------------------------------- /60-69/62. Intersection of Two Linked Lists(Easy)/160_statement.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/60-69/62. Intersection of Two Linked Lists(Easy)/160_statement.png -------------------------------------------------------------------------------- /60-69/62. Intersection of Two Linked Lists(Easy)/2.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/60-69/62. Intersection of Two Linked Lists(Easy)/2.jpeg -------------------------------------------------------------------------------- /60-69/63. Middle of the Linked List(Easy)/876.middle-of-the-linked-list.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=876 lang=cpp 3 | * 4 | * [876] Middle of the Linked List 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for singly-linked list. 10 | * struct ListNode { 11 | * int val; 12 | * ListNode *next; 13 | * ListNode() : val(0), next(nullptr) {} 14 | * ListNode(int x) : val(x), next(nullptr) {} 15 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | ListNode* middleNode(ListNode* head) { 21 | if (head == nullptr) 22 | return head; 23 | ListNode *fast, *slow; 24 | fast = slow = head; 25 | while (fast->next != nullptr && fast->next->next != nullptr) 26 | { 27 | fast = fast->next->next; 28 | slow = slow->next; 29 | } 30 | // 偶数个 31 | if (fast->next != nullptr && fast->next->next == nullptr) 32 | return slow->next; 33 | else 34 | return slow; 35 | } 36 | }; 37 | // @lc code=end 38 | 39 | -------------------------------------------------------------------------------- /60-69/63. Middle of the Linked List(Easy)/lc-midlist1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/60-69/63. Middle of the Linked List(Easy)/lc-midlist1.jpg -------------------------------------------------------------------------------- /60-69/63. Middle of the Linked List(Easy)/lc-midlist2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/60-69/63. Middle of the Linked List(Easy)/lc-midlist2.jpg -------------------------------------------------------------------------------- /60-69/64. Reverse Linked List II(Medium)/rev2ex2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/60-69/64. Reverse Linked List II(Medium)/rev2ex2.jpg -------------------------------------------------------------------------------- /60-69/65. Remove Duplicates from Sorted List(Easy)/83.remove-duplicates-from-sorted-list.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=83 lang=cpp 3 | * 4 | * [83] Remove Duplicates from Sorted List 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for singly-linked list. 10 | * struct ListNode { 11 | * int val; 12 | * ListNode *next; 13 | * ListNode() : val(0), next(nullptr) {} 14 | * ListNode(int x) : val(x), next(nullptr) {} 15 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | ListNode* deleteDuplicates(ListNode* head) { 21 | ListNode *dummy = new ListNode(-999); 22 | ListNode *d = dummy; 23 | dummy->next = head; 24 | ListNode *p = head; 25 | while (p != nullptr) 26 | { 27 | if (d->val != p->val) 28 | { 29 | d->next = p; 30 | d = p; 31 | } 32 | p = p->next; 33 | } 34 | d->next = p; // 最后一个重复的节点删除 35 | return dummy->next; 36 | } 37 | }; 38 | // @lc code=end 39 | 40 | -------------------------------------------------------------------------------- /60-69/65. Remove Duplicates from Sorted List(Easy)/list1.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/60-69/65. Remove Duplicates from Sorted List(Easy)/list1.jpeg -------------------------------------------------------------------------------- /60-69/65. Remove Duplicates from Sorted List(Easy)/list2.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/60-69/65. Remove Duplicates from Sorted List(Easy)/list2.jpeg -------------------------------------------------------------------------------- /60-69/66. Partition List(Medium)/partition.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/60-69/66. Partition List(Medium)/partition.jpg -------------------------------------------------------------------------------- /60-69/67. Copy List with Random Pointer(Medium)/e1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/60-69/67. Copy List with Random Pointer(Medium)/e1.png -------------------------------------------------------------------------------- /60-69/67. Copy List with Random Pointer(Medium)/e2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/60-69/67. Copy List with Random Pointer(Medium)/e2.png -------------------------------------------------------------------------------- /60-69/67. Copy List with Random Pointer(Medium)/e3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/60-69/67. Copy List with Random Pointer(Medium)/e3.png -------------------------------------------------------------------------------- /BFS/129.求根节点到叶节点数字之和.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=129 lang=cpp 3 | * 4 | * [129] 求根节点到叶节点数字之和 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | int sumNumbers(TreeNode* root) { 22 | if (root == nullptr) return 0; 23 | int sum = 0; 24 | traceback(root, sum, 0); 25 | return sum; 26 | } 27 | 28 | void traceback(TreeNode* root, int& sum, int num) { 29 | if (root == nullptr) return; 30 | num = num * 10 + root->val; 31 | if (root->left == nullptr && root->right == nullptr) 32 | { 33 | sum += num; 34 | } 35 | traceback(root->left, sum, num); 36 | traceback(root->right, sum, num); 37 | } 38 | }; 39 | // @lc code=end 40 | 41 | -------------------------------------------------------------------------------- /BFS/279.完全平方数.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=279 lang=cpp 3 | * 4 | * [279] 完全平方数 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int numSquares(int n) { 11 | // 背包问题 12 | vector dp(n + 1, INT_MAX); 13 | dp[0] = 0; 14 | dp[1] = 1; 15 | for (int i = 2; i < n+1; i++) { 16 | for (int j = 1; j <= sqrt(i); j++) { 17 | dp[i] = min(dp[i], dp[i - j*j] + 1); 18 | } 19 | } 20 | return dp[n]; 21 | } 22 | }; 23 | // @lc code=end 24 | 25 | -------------------------------------------------------------------------------- /BFS/933.最近的请求次数.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=933 lang=cpp 3 | * 4 | * [933] 最近的请求次数 5 | */ 6 | 7 | // @lc code=start 8 | class RecentCounter { 9 | public: 10 | RecentCounter() { 11 | } 12 | 13 | int ping(int t) { 14 | q.push(t); 15 | while(q.front() < t-3000) 16 | q.pop(); 17 | return q.size(); 18 | } 19 | 20 | private: 21 | queue q; 22 | }; 23 | 24 | /** 25 | * Your RecentCounter object will be instantiated and called as such: 26 | * RecentCounter* obj = new RecentCounter(); 27 | * int param_1 = obj->ping(t); 28 | */ 29 | // @lc code=end 30 | 31 | -------------------------------------------------------------------------------- /DFS/100.相同的树.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=100 lang=cpp 3 | * 4 | * [100] 相同的树 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | bool isSameTree(TreeNode* p, TreeNode* q) { 22 | if (p == nullptr && q == nullptr) return true; 23 | if (p == nullptr || q == nullptr) return false; 24 | if (p->val != q->val) return false; 25 | return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); 26 | } 27 | }; 28 | // @lc code=end 29 | 30 | -------------------------------------------------------------------------------- /DFS/101.对称二叉树.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=101 lang=cpp 3 | * 4 | * [101] 对称二叉树 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | bool isSymmetric(TreeNode* root) { 22 | return symmetric(root->left, root->right); 23 | } 24 | 25 | bool symmetric(TreeNode* p, TreeNode* q) { 26 | if (p == nullptr && q == nullptr) return true; 27 | if (p == nullptr || q == nullptr) return false; 28 | if (p->val != q->val) return false; 29 | return symmetric(p->left, q->right) && symmetric(p->right, q->left); 30 | } 31 | }; 32 | // @lc code=end 33 | 34 | -------------------------------------------------------------------------------- /DFS/1022.从根到叶的二进制数之和.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=1022 lang=cpp 3 | * 4 | * [1022] 从根到叶的二进制数之和 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | int sumRootToLeaf(TreeNode* root) { 22 | int sum = 0; 23 | dfs(root, 0, sum); 24 | return sum; 25 | } 26 | 27 | void dfs(TreeNode* root, int path, int& sum) { 28 | if (root == nullptr) 29 | return; 30 | int val = (path << 1) | root->val; 31 | if (root->left == nullptr && root->right == nullptr) { 32 | sum += val; 33 | } 34 | dfs(root->left, val, sum); 35 | dfs(root->right, val, sum); 36 | } 37 | 38 | }; 39 | // @lc code=end 40 | 41 | -------------------------------------------------------------------------------- /DFS/1030.距离顺序排列矩阵单元格.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=1030 lang=cpp 3 | * 4 | * [1030] 距离顺序排列矩阵单元格 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector> allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) { 11 | vector>> cup(200); 12 | for (int i = 0; i < rows; i++) { 13 | for (int j = 0; j < cols; j++) { 14 | int a = abs(i - rCenter); 15 | int b = abs(j - cCenter); 16 | int dis = a + b; 17 | cup[dis].push_back({ i, j }); 18 | } 19 | } 20 | vector> ans; 21 | for (int i = 0; i < cup.size(); i++) { 22 | for (int j = 0; j < cup[i].size(); j++) { 23 | ans.push_back(cup[i][j]); 24 | } 25 | } 26 | return ans; 27 | 28 | } 29 | }; 30 | // @lc code=end 31 | 32 | -------------------------------------------------------------------------------- /DFS/104.二叉树的最大深度.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=104 lang=cpp 3 | * 4 | * [104] 二叉树的最大深度 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | int maxDepth(TreeNode* root) { 22 | if (root == nullptr) return 0; 23 | int a = maxDepth(root->left); 24 | int b = maxDepth(root->right); 25 | return max(a, b) + 1; 26 | } 27 | }; 28 | // @lc code=end 29 | 30 | -------------------------------------------------------------------------------- /DFS/108.将有序数组转换为二叉搜索树.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=108 lang=cpp 3 | * 4 | * [108] 将有序数组转换为二叉搜索树 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | 22 | TreeNode* sortedArrayToBST(vector& nums) { 23 | return genBST(nums, 0, nums.size() - 1); 24 | } 25 | 26 | TreeNode* genBST(vector& nums, int begin, int end) { 27 | if (begin > end) return nullptr; 28 | int mid = (end + begin) / 2; 29 | TreeNode* root = new TreeNode(nums[mid]); 30 | root->left = genBST(nums, begin, mid-1); 31 | root->right = genBST(nums, mid+1, end); 32 | return root; 33 | } 34 | }; 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | // @lc code=end 44 | 45 | -------------------------------------------------------------------------------- /DFS/110.平衡二叉树.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=110 lang=cpp 3 | * 4 | * [110] 平衡二叉树 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | bool isBalanced(TreeNode* root) { 22 | if (root == nullptr) return true; 23 | return dfs(root) != -1; 24 | } 25 | 26 | int dfs(TreeNode* root) { 27 | if (root == nullptr) 28 | return 0; 29 | int a = dfs(root->left); 30 | int b = dfs(root->right); 31 | if (a == -1 || b == -1) return -1; 32 | if (abs(a-b) > 1) return -1; 33 | return max(a, b) + 1; 34 | } 35 | }; 36 | // @lc code=end 37 | 38 | -------------------------------------------------------------------------------- /DFS/112.路径总和.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=112 lang=cpp 3 | * 4 | * [112] 路径总和 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | bool hasPathSum(TreeNode* root, int targetSum) { 22 | int sum = 0; 23 | return traceback(root, targetSum, sum); 24 | } 25 | 26 | bool traceback(TreeNode* root, int targetSum, int sum) { 27 | if (root == nullptr) return false; 28 | if (root->left == nullptr && root->right == nullptr) 29 | return (sum + root->val) == targetSum; 30 | return traceback(root->left, targetSum, sum + root->val) || 31 | traceback(root->right, targetSum, sum + root->val); 32 | 33 | } 34 | }; 35 | // @lc code=end 36 | 37 | -------------------------------------------------------------------------------- /DFS/129.求根节点到叶节点数字之和.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=129 lang=cpp 3 | * 4 | * [129] 求根节点到叶节点数字之和 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | int sumNumbers(TreeNode* root) { 22 | if (root == nullptr) return 0; 23 | int sum = 0; 24 | traceback(root, sum, 0); 25 | return sum; 26 | } 27 | 28 | void traceback(TreeNode* root, int& sum, int num) { 29 | if (root == nullptr) return; 30 | num = num * 10 + root->val; 31 | if (root->left == nullptr && root->right == nullptr) 32 | { 33 | sum += num; 34 | } 35 | traceback(root->left, sum, num); 36 | traceback(root->right, sum, num); 37 | } 38 | }; 39 | // @lc code=end 40 | 41 | -------------------------------------------------------------------------------- /DFS/733.图像渲染.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=733 lang=cpp 3 | * 4 | * [733] 图像渲染 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector> floodFill(vector>& image, int sr, int sc, int color) { 11 | int pixel = image[sr][sc]; 12 | if (pixel == color) 13 | return image; 14 | dfs(image, sr, sc, pixel, color); 15 | return image; 16 | } 17 | 18 | void dfs(vector>& image, int i, int j, int pixel, int color) { 19 | // cout << i << " " << j << endl; 20 | if (i < 0 || j < 0) 21 | return; 22 | if (i >= image.size() || j >= image[0].size()) 23 | return; 24 | if (image[i][j] == pixel) { 25 | image[i][j] = color; 26 | dfs(image, i-1, j, pixel, color); 27 | dfs(image, i+1, j, pixel, color); 28 | dfs(image, i, j-1, pixel, color); 29 | dfs(image, i, j+1, pixel, color); 30 | } 31 | } 32 | }; 33 | // @lc code=end 34 | 35 | -------------------------------------------------------------------------------- /DFS/744.寻找比目标字母大的最小字母.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=744 lang=cpp 3 | * 4 | * [744] 寻找比目标字母大的最小字母 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | char nextGreatestLetter(vector& letters, char target) { 11 | // if (target > letters[letters.size() - 1]) 12 | // return letters[0]; 13 | // for (char c : letters) { 14 | // if (c > target) 15 | // return c; 16 | // } 17 | // return letters[0]; 18 | vector::iterator c = upper_bound(letters.begin(), letters.end(), target); 19 | if (c == letters.end()) 20 | return letters[0]; 21 | return *c; 22 | } 23 | }; 24 | // @lc code=end 25 | 26 | -------------------------------------------------------------------------------- /DFS/766.托普利茨矩阵.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=766 lang=cpp 3 | * 4 | * [766] 托普利茨矩阵 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | bool isToeplitzMatrix(vector>& matrix) { 11 | int n = matrix.size(); 12 | int m = matrix[0].size(); 13 | vector> visited(n, vector(m, false)); 14 | return dfs(matrix, 0, matrix[0].size() - 1, visited); 15 | } 16 | 17 | bool dfs(const vector>& matrix, int i, int j, vector>& visited) { 18 | if (j <= 0 || i >= matrix.size() -1) 19 | return true; 20 | if (visited[i][j]) 21 | return true; 22 | if (matrix[i][j-1] != matrix[i+1][j]) 23 | return false; 24 | visited[i][j] = true; 25 | return dfs(matrix, i, j-1, visited) && dfs(matrix, i+1, j, visited); 26 | } 27 | }; 28 | // @lc code=end 29 | 30 | -------------------------------------------------------------------------------- /DFS/922.按奇偶排序数组-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=922 lang=cpp 3 | * 4 | * [922] 按奇偶排序数组 II 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector sortArrayByParityII(vector& nums) { 11 | int i = 0; 12 | int j = 1; 13 | for (int n : nums) { 14 | int o = n & 0xFFFF; 15 | // cout << n << " " << o << " " << i << " " << j << " "; 16 | if (o % 2 == 0) { 17 | o = o << 16; 18 | // cout << o << endl; 19 | nums[i] = nums[i] | o; 20 | i += 2; 21 | } else { 22 | o = o << 16; 23 | // cout << o << endl; 24 | nums[j] = nums[j] | o; 25 | j += 2; 26 | } 27 | } 28 | for (int i = 0; i < nums.size(); i++) { 29 | // cout << i << "." << nums[i] << " " << (nums[i] >> 16) << endl; 30 | nums[i] = nums[i] >> 16; 31 | } 32 | return nums; 33 | } 34 | }; 35 | // @lc code=end 36 | 37 | -------------------------------------------------------------------------------- /DFS/999.可以被一步捕获的棋子数.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=999 lang=cpp 3 | * 4 | * [999] 可以被一步捕获的棋子数 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int numRookCaptures(vector>& board) { 11 | for (int i = 0; i < 8; i++) { 12 | for (int j = 0; j < 8; j++) { 13 | if (board[i][j] == 'R') { 14 | return dfs(board, i, j); 15 | } 16 | } 17 | } 18 | return 0; 19 | } 20 | 21 | int dfs(vector>& board, int i, int j) { 22 | int count = 0; 23 | vector dx = { 0, 0, -1, 1 }; 24 | vector dy = { -1, 1, 0, 0 }; 25 | for (int k = 0; k < 4; k++) 26 | { 27 | int x = j; 28 | int y = i; 29 | while (x >= 0 && x < 8 && y >= 0 && y < 8 && board[y][x] != 'B') 30 | { 31 | if (board[y][x] == 'p') { 32 | count++; 33 | break; 34 | } 35 | x += dx[k]; 36 | y += dy[k]; 37 | } 38 | } 39 | return count; 40 | } 41 | }; 42 | // @lc code=end 43 | 44 | -------------------------------------------------------------------------------- /二分查找/153.寻找旋转排序数组中的最小值.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=153 lang=cpp 3 | * 4 | * [153] 寻找旋转排序数组中的最小值 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int findMin(vector& nums) { 11 | int n = nums.size(); 12 | int left = 0; 13 | int right = n - 1; 14 | while (left < right) { 15 | int mid = left + (right - left) / 2; 16 | if (nums[right] < nums[mid]) { 17 | left = mid + 1; 18 | } else { 19 | right = mid; 20 | } 21 | } 22 | return nums[left]; 23 | // 1 0 24 | } 25 | }; 26 | // @lc code=end 27 | 28 | -------------------------------------------------------------------------------- /二分查找/162.寻找峰值.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=162 lang=cpp 3 | * 4 | * [162] 寻找峰值 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int findPeakElement(vector& nums) { 11 | // mid 附近递增,峰值在右 mid附近递减,峰值在左 12 | if (nums.size() == 1) 13 | return 0; 14 | int left = 0; 15 | int right = nums.size() - 1; 16 | while (left < right) 17 | { 18 | int mid = left + (right - left) / 2; 19 | if (nums[mid] > nums[mid + 1]) { // mid是峰顶 或 下坡 20 | right = mid; 21 | } else { // 上坡,mid并且一定不是峰顶 22 | left = mid + 1; 23 | } 24 | } 25 | return left; 26 | } 27 | 28 | }; 29 | // @lc code=end 30 | 31 | -------------------------------------------------------------------------------- /二分查找/240.搜索二维矩阵-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=240 lang=cpp 3 | * 4 | * [240] 搜索二维矩阵 II 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | bool searchMatrix(vector>& matrix, int target) { 11 | int m = matrix.size(); 12 | int n = matrix[0].size(); 13 | int x = n - 1; 14 | int y = 0; 15 | while (x >= 0 && y < m) 16 | { 17 | if (matrix[y][x] == target) 18 | return true; 19 | else if (matrix[y][x] < target) { 20 | y++; 21 | } else if (matrix[y][x] > target) { 22 | x--; 23 | } 24 | } 25 | return false; 26 | } 27 | }; 28 | // @lc code=end 29 | 30 | -------------------------------------------------------------------------------- /二分查找/275.h-指数-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=275 lang=cpp 3 | * 4 | * [275] H 指数 II 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int hIndex(vector& citations) { 11 | int m = citations.size(); 12 | int left = 0; 13 | int right = m - 1; 14 | while (left < right) 15 | { 16 | int mid = left + (right - left) / 2; 17 | if (citations[mid] >= (m - mid)) { 18 | right = mid; 19 | } else { 20 | left = mid + 1; 21 | } 22 | } 23 | if (citations[right] == 0) return 0; // testcase: [0] 24 | return m - right; 25 | } 26 | }; 27 | // @lc code=end 28 | 29 | -------------------------------------------------------------------------------- /二分查找/278.第一个错误的版本.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=278 lang=cpp 3 | * 4 | * [278] 第一个错误的版本 5 | */ 6 | 7 | // @lc code=start 8 | // The API isBadVersion is defined for you. 9 | // bool isBadVersion(int version); 10 | 11 | class Solution { 12 | public: 13 | int firstBadVersion(int n) { 14 | int left = 0; 15 | int right = n; 16 | while (left < right) 17 | { 18 | int mid = left + (right - left) / 2; 19 | if (isBadVersion(mid)) { 20 | right = mid; 21 | } else { 22 | left = mid + 1; 23 | } 24 | } 25 | return right; 26 | } 27 | }; 28 | // @lc code=end 29 | 30 | -------------------------------------------------------------------------------- /二分查找/367.有效的完全平方数.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=367 lang=cpp 3 | * 4 | * [367] 有效的完全平方数 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | bool isPerfectSquare(int num) { 11 | if (num == 1) return true; 12 | int left = 0; 13 | int right = num / 2; 14 | while (left <= right) 15 | { 16 | long mid = left + (right - left) / 2; 17 | if (mid * mid == num) { 18 | return true; 19 | } else if (mid * mid > num) { 20 | right = mid - 1; 21 | } else { 22 | left = mid + 1; 23 | } 24 | } 25 | return false; 26 | } 27 | }; 28 | // @lc code=end 29 | 30 | -------------------------------------------------------------------------------- /二分查找/374.猜数字大小.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=374 lang=cpp 3 | * 4 | * [374] 猜数字大小 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Forward declaration of guess API. 10 | * @param num your guess 11 | * @return -1 if num is higher than the picked number 12 | * 1 if num is lower than the picked number 13 | * otherwise return 0 14 | * int guess(int num); 15 | */ 16 | 17 | class Solution { 18 | public: 19 | int guessNumber(int n) { 20 | int left = 1; 21 | int right = n; 22 | while (left <= right) 23 | { 24 | int mid = left + (right - left) / 2; 25 | if (guess(mid) == 0) { 26 | return mid; 27 | } else if (guess(mid) == 1) { 28 | left = mid + 1; 29 | } else if (guess(mid) == -1) { 30 | right = mid - 1; 31 | } 32 | } 33 | return -1; 34 | } 35 | }; 36 | // @lc code=end 37 | 38 | -------------------------------------------------------------------------------- /二分查找/441.排列硬币.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=441 lang=cpp 3 | * 4 | * [441] 排列硬币 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int arrangeCoins(int n) { 11 | int left = 1; 12 | int right = n; 13 | int ans = 0; 14 | while (left <= right) { 15 | long mid = left + (right - left) / 2; 16 | if (sum(mid) > n) { 17 | right = mid - 1; 18 | } else if (sum(mid) < n) { 19 | ans = mid; 20 | left = mid + 1; 21 | } else { 22 | return mid; 23 | } 24 | } 25 | return ans; 26 | } 27 | 28 | long sum(long n) { 29 | // 等差数列求和公式 30 | // Sn=n(a1+an)/2 31 | return (1 + n) * n / 2; 32 | } 33 | }; 34 | // @lc code=end 35 | 36 | -------------------------------------------------------------------------------- /二分查找/69.x-的平方根.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=69 lang=cpp 3 | * 4 | * [69] x 的平方根 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int mySqrt(int x) { 11 | int left = 0; 12 | int right = x >> 1; 13 | 14 | while (left <= right) { 15 | long mid = left + ((right - left) >> 1); 16 | if (mid*mid > x) { 17 | if ((mid - 1) * (mid - 1) <= x) 18 | return mid - 1; 19 | right = mid - 1; 20 | } else if (mid*mid < x) { 21 | if ((mid + 1) * (mid + 1) > x) 22 | return mid; 23 | left = mid + 1; 24 | } else { 25 | return mid; 26 | } 27 | } 28 | return 1; // testcase 1 return 1 29 | } 30 | }; 31 | // @lc code=end 32 | 33 | -------------------------------------------------------------------------------- /二分查找/910.最小差值-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=910 lang=cpp 3 | * 4 | * [910] 最小差值 II 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int smallestRangeII(vector& nums, int k) { 11 | sort(nums.begin(), nums.end()); 12 | int n = nums.size(); 13 | int E = nums[n-1] - nums[0]; 14 | // 从1到nums.size()的长度中任意一点都有可能是中间点 15 | for (int i = 1; i < n; i++) { 16 | int min_val = min(nums[0] + k, nums[i] - k); 17 | int max_val = max(nums[n-1] - k, nums[i-1] + k); 18 | E = min(E, max_val-min_val); 19 | } 20 | return E; 21 | } 22 | }; 23 | // @lc code=end 24 | 25 | -------------------------------------------------------------------------------- /二分查找/912.排序数组.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=912 lang=cpp 3 | * 4 | * [912] 排序数组 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector sortArray(vector& nums) { 11 | sort(nums.begin(), nums.end()); 12 | return nums; 13 | } 14 | }; 15 | // @lc code=end 16 | 17 | -------------------------------------------------------------------------------- /二叉搜索树/1038.binary-search-tree-to-greater-sum-tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1038 lang=cpp 3 | * 4 | * [1038] Binary Search Tree to Greater Sum Tree 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | TreeNode* bstToGst(TreeNode* root) { 22 | int plus = 0; 23 | cvtBT(root, plus); 24 | return root; 25 | } 26 | 27 | void cvtBT(TreeNode* root, int& plus) { 28 | if (root == nullptr) return; 29 | 30 | cvtBT(root->right, plus); 31 | root->val = root->val + plus; 32 | plus = root->val; 33 | cvtBT(root->left, plus); 34 | } 35 | }; 36 | // @lc code=end 37 | 38 | -------------------------------------------------------------------------------- /二叉搜索树/538.convert-bst-to-greater-tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=538 lang=cpp 3 | * 4 | * [538] Convert BST to Greater Tree 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | 22 | TreeNode* convertBST(TreeNode* root) { 23 | int plus = 0; 24 | cvtBT(root, plus); 25 | return root; 26 | } 27 | 28 | void cvtBT(TreeNode* root, int& plus) { 29 | if (root == nullptr) return; 30 | 31 | cvtBT(root->right, plus); 32 | root->val = root->val + plus; 33 | plus = root->val; 34 | cvtBT(root->left, plus); 35 | } 36 | }; 37 | // @lc code=end 38 | 39 | -------------------------------------------------------------------------------- /二叉搜索树/653.两数之和-iv-输入-bst.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=653 lang=cpp 3 | * 4 | * [653] 两数之和 IV - 输入 BST 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | bool findTarget(TreeNode* root, int k) { 22 | if (root == nullptr) 23 | return false; 24 | if (st.find(k - root->val) != st.end()) 25 | return true; 26 | st.insert(root->val); 27 | return findTarget(root->left, k) || findTarget(root->right, k); 28 | } 29 | private: 30 | unordered_set st; 31 | }; 32 | // @lc code=end 33 | 34 | -------------------------------------------------------------------------------- /二叉搜索树/700.search-in-a-binary-search-tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=700 lang=cpp 3 | * 4 | * [700] Search in a Binary Search Tree 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | TreeNode* searchBST(TreeNode* root, int val) { 22 | if (root == nullptr) 23 | return nullptr; 24 | if (root->val > val) 25 | return searchBST(root->left, val); 26 | else if (root->val < val) 27 | return searchBST(root->right, val); 28 | return root; 29 | } 30 | }; 31 | // @lc code=end 32 | 33 | -------------------------------------------------------------------------------- /二叉搜索树/701.insert-into-a-binary-search-tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=701 lang=cpp 3 | * 4 | * [701] Insert into a Binary Search Tree 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | TreeNode* insertIntoBST(TreeNode* root, int val) { 22 | if (root == nullptr) 23 | return new TreeNode(val); 24 | 25 | if (root->val > val) 26 | root->left = insertIntoBST(root->left, val); 27 | if (root->val < val) 28 | root->right = insertIntoBST(root->right, val); 29 | return root; 30 | } 31 | }; 32 | // @lc code=end 33 | 34 | -------------------------------------------------------------------------------- /二叉搜索树/96.unique-binary-search-trees.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=96 lang=cpp 3 | * 4 | * [96] Unique Binary Search Trees 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int numTrees(int n) { 11 | return subNums(1, n); 12 | } 13 | 14 | int subNums(int left, int right) { 15 | 16 | 17 | if (left >= right) 18 | return 1; 19 | int key = right - left + 1; 20 | if (map.find(key) != map.end()) 21 | { 22 | return map[key]; 23 | } 24 | int sum = 0; 25 | for (size_t i = left; i < right+1; i++) 26 | { 27 | int lo = subNums(left, i-1); 28 | int ri = subNums(i+1, right); 29 | sum += lo * ri; 30 | } 31 | map.insert({ key, sum }); 32 | return sum; 33 | } 34 | 35 | private: 36 | unordered_map map; 37 | }; 38 | // @lc code=end 39 | 40 | -------------------------------------------------------------------------------- /二叉树/144.二叉树的前序遍历.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=144 lang=cpp 3 | * 4 | * [144] 二叉树的前序遍历 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | vector preorderTraversal(TreeNode* root) { 22 | vector ans; 23 | traversal(root, ans); 24 | return ans; 25 | } 26 | 27 | void traversal(TreeNode* root, vector& ans) { 28 | if (root == nullptr) return; 29 | ans.push_back(root->val); 30 | traversal(root->left, ans); 31 | traversal(root->right, ans); 32 | } 33 | }; 34 | // @lc code=end 35 | 36 | -------------------------------------------------------------------------------- /二叉树/145.二叉树的后序遍历.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=145 lang=cpp 3 | * 4 | * [145] 二叉树的后序遍历 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | vector postorderTraversal(TreeNode* root) { 22 | vector ans; 23 | traversal(root, ans); 24 | return ans; 25 | } 26 | 27 | void traversal(TreeNode* root, vector& ans) { 28 | if (root == nullptr) return; 29 | traversal(root->left, ans); 30 | traversal(root->right, ans); 31 | ans.push_back(root->val); 32 | } 33 | }; 34 | // @lc code=end 35 | 36 | -------------------------------------------------------------------------------- /二叉树/226.invert-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=226 lang=cpp 3 | * 4 | * [226] Invert Binary Tree 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | TreeNode* invertTree(TreeNode* root) { 22 | if (root == nullptr) 23 | { 24 | return nullptr; 25 | } 26 | TreeNode* a = root->left; 27 | root->left = root->right; 28 | root->right = a; 29 | 30 | invertTree(root->left); 31 | invertTree(root->right); 32 | return root; 33 | } 34 | }; 35 | // @lc code=end 36 | 37 | -------------------------------------------------------------------------------- /二叉树/236.lowest-common-ancestor-of-a-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=236 lang=cpp 3 | * 4 | * [236] Lowest Common Ancestor of a Binary Tree 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 15 | * }; 16 | */ 17 | class Solution { 18 | public: 19 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 20 | if (root == nullptr) return nullptr; 21 | 22 | if (p == root || q == root) 23 | return root; 24 | 25 | TreeNode* a = lowestCommonAncestor(root->left, p, q); 26 | TreeNode* b = lowestCommonAncestor(root->right, p, q); 27 | if (a != nullptr && b != nullptr) 28 | return root; 29 | 30 | return a != nullptr ? a : b; 31 | } 32 | }; 33 | // @lc code=end 34 | 35 | -------------------------------------------------------------------------------- /二叉树/543.diameter-of-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=543 lang=cpp 3 | * 4 | * [543] Diameter of Binary Tree 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | int diameterOfBinaryTree(TreeNode* root) { 22 | depth(root); 23 | return maxd; 24 | } 25 | 26 | int depth(TreeNode* root) { 27 | if (root == nullptr) 28 | return 0; 29 | int left = depth(root->left); 30 | int right = depth(root->right); 31 | 32 | // 最大路径为 A 形, 若顶点为自己 33 | maxd = max(maxd, left + right); 34 | return 1 + max(left, right); 35 | } 36 | private: 37 | int maxd = 0; 38 | }; 39 | // @lc code=end 40 | 41 | -------------------------------------------------------------------------------- /动态规划/120.triangle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=120 lang=cpp 3 | * 4 | * [120] Triangle 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int minimumTotal(vector>& triangle) { 11 | int n = triangle.size(); 12 | if (n == 1) 13 | return triangle[0][0]; 14 | 15 | vector> dp(n, vector(n)); 16 | dp[0][0] = triangle[0][0]; 17 | 18 | for (int i = 1; i < n; i++) 19 | { 20 | for (int j = 0; j <= i; j++) 21 | { 22 | if (j == 0) 23 | dp[i][j] = dp[i-1][j] + triangle[i][j]; 24 | else if (j == i) 25 | dp[i][j] = dp[i-1][j-1] + triangle[i][j]; 26 | else 27 | dp[i][j] = min(dp[i-1][j-1], dp[i-1][j]) + triangle[i][j]; 28 | } 29 | } 30 | 31 | int total = INT_MAX; 32 | for (int j = 0; j < n; j++) { 33 | total = dp[n-1][j] < total ? dp[n-1][j] : total; 34 | } 35 | return total; 36 | } 37 | 38 | }; 39 | // @lc code=end 40 | 41 | -------------------------------------------------------------------------------- /动态规划/198.house-robber.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=198 lang=cpp 3 | * 4 | * [198] House Robber 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int rob(vector& nums) { 11 | int n = nums.size(); 12 | vector dp(n); 13 | if (nums.size() == 1) return nums[0]; 14 | dp[0] = nums[0]; 15 | dp[1] = max(nums[0], nums[1]); 16 | for (int i = 2; i < n; i++) 17 | { 18 | dp[i] = max(dp[i-2] + nums[i], dp[i-1]); 19 | } 20 | return dp[n-1]; 21 | 22 | } 23 | }; 24 | // @lc code=end 25 | 26 | -------------------------------------------------------------------------------- /动态规划/213.house-robber-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=213 lang=cpp 3 | * 4 | * [213] House Robber II 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int rob(vector& nums) { 11 | int n = nums.size(); 12 | if (n <= 1) 13 | return nums[0]; 14 | 15 | return max(rob(nums, 0, n-2), rob(nums, 1, n-1)); 16 | } 17 | 18 | int rob(const vector& nums, int start, int end) { 19 | int n = end - start + 1; 20 | if (n == 1) 21 | return nums[start]; 22 | vector dp(nums.size() + 2); // dp[i+2] 为 nums[i] 最多 23 | for (int i = start; i < end+1; i++) 24 | { 25 | dp[i+2] = max(dp[i] + nums[i], dp[i+1]); 26 | } 27 | return dp[end+2]; 28 | } 29 | }; 30 | // @lc code=end 31 | 32 | -------------------------------------------------------------------------------- /动态规划/337.house-robber-iii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=337 lang=cpp 3 | * 4 | * [337] House Robber III 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | int rob(TreeNode* root) { 22 | } 23 | 24 | int rob(TreeNode* root, bool r) { 25 | } 26 | }; 27 | // @lc code=end 28 | 29 | -------------------------------------------------------------------------------- /动态规划/494.target-sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=494 lang=cpp 3 | * 4 | * [494] Target Sum 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int findTargetSumWays(vector& nums, int target) { 11 | return find(nums, target, 0); 12 | } 13 | 14 | int find(const vector& nums, int target, int cur) { 15 | if (cur == nums.size() - 1) 16 | { 17 | if (nums[cur] == 0 && target == 0) 18 | return 2; // 0 前面正负皆可 19 | 20 | if (nums[cur] == target || 0 - nums[cur] == target) 21 | return 1; 22 | return 0; 23 | } 24 | 25 | int pos = find(nums, target - nums[cur], cur + 1); 26 | int nag = find(nums, target + nums[cur], cur + 1); 27 | return pos + nag; 28 | } 29 | }; 30 | // @lc code=end 31 | 32 | -------------------------------------------------------------------------------- /动态规划/509.fibonacci-number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=509 lang=cpp 3 | * 4 | * [509] Fibonacci Number 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int fib(int n) { 11 | if (n == 0) return 0; 12 | if (n == 1) return 1; 13 | 14 | int pre1 = 0; 15 | int pre2 = 1; 16 | int sum = 0; 17 | for (size_t i = 0; i < n-1; i++) 18 | { 19 | sum = pre1 + pre2; 20 | pre1 = pre2; 21 | pre2 = sum; 22 | } 23 | return sum; 24 | 25 | } 26 | }; 27 | // @lc code=end 28 | 29 | -------------------------------------------------------------------------------- /动态规划/516.longest-palindromic-subsequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=516 lang=cpp 3 | * 4 | * [516] Longest Palindromic Subsequence 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int longestPalindromeSubseq(string s) { 11 | int n = s.length(); 12 | if (n <= 0) 13 | return 0; 14 | vector> dp(n, vector(n)); 15 | // base case 每一个字符都是自身的子序列 16 | for (size_t i = 0; i < n; i++) 17 | dp[i][i] = 1; 18 | 19 | for (int i = n-1; i >= 0; i--) 20 | { 21 | for (int j = i+1; j < n; j++) 22 | { 23 | if (s[i] == s[j]) 24 | dp[i][j] = dp[i+1][j-1] + 2; 25 | else 26 | dp[i][j] = max(dp[i+1][j], dp[i][j-1]); 27 | } 28 | 29 | } 30 | return dp[0][n-1]; 31 | } 32 | }; 33 | // @lc code=end 34 | 35 | -------------------------------------------------------------------------------- /动态规划/518.coin-change-2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=518 lang=cpp 3 | * 4 | * [518] Coin Change 2 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int change(int amount, vector& coins) { 11 | vector dp(amount + 1); 12 | // base case 13 | for (int j = 0; j < coins.size(); j++) { 14 | if (coins[j] < amount + 1) 15 | { 16 | dp[coins[j]] = 1; 17 | } 18 | } 19 | for (int i = 1; i < amount + 1; i++) 20 | { 21 | for (int j = 0; j < coins.size(); j++) 22 | { 23 | if (i - coins[j] >= 0) 24 | { 25 | dp[i] += dp[i - coins[j]]; 26 | } 27 | } 28 | } 29 | 30 | return dp[amount]; 31 | } 32 | }; 33 | // @lc code=end 34 | 35 | -------------------------------------------------------------------------------- /动态规划/518.零钱兑换-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=518 lang=cpp 3 | * 4 | * [518] 零钱兑换 II 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | 11 | int change(int amount, vector& coins) { 12 | int n = coins.size(); 13 | vector dp(amount + 1); 14 | // base case 15 | dp[0] = 1; 16 | 17 | for (int i = 0; i < n; i++) 18 | { 19 | for (int j = coins[i]; j < amount + 1; j++) 20 | { 21 | // 不放入 dp[j] 为自身,不改变组合数 22 | // 放入则 加上 j-coins[i] 的组合数 23 | dp[j] += dp[j-coins[i]]; 24 | } 25 | } 26 | 27 | return dp[amount]; 28 | } 29 | }; 30 | // @lc code=end 31 | 32 | -------------------------------------------------------------------------------- /动态规划/583.delete-operation-for-two-strings.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=583 lang=cpp 3 | * 4 | * [583] Delete Operation for Two Strings 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int minDistance(string word1, string word2) { 11 | // 求 word1 和 word2 的最长公共子序列 长度 ln 12 | // word1.length + word2.length - 2 * ln 即为结果 13 | int ln = LCS(word1, word2); 14 | return word1.length() + word2.length() - 2 * ln; 15 | } 16 | 17 | int LCS(const string& word1, const string& word2) 18 | { 19 | int n1 = word1.length(); 20 | int n2 = word2.length(); 21 | vector> dp(n1+1, vector(n2+1)); 22 | for (size_t i = 1; i < n1+1; i++) 23 | { 24 | for (size_t j = 1; j < n2+1; j++) 25 | { 26 | if (word1[i-1] == word2[j-1]) 27 | { 28 | dp[i][j] = 1 + dp[i-1][j-1]; 29 | } 30 | else 31 | { 32 | dp[i][j] = max(dp[i][j-1], dp[i-1][j]); 33 | } 34 | } 35 | } 36 | return dp[n1][n2]; 37 | } 38 | }; 39 | // @lc code=end 40 | 41 | -------------------------------------------------------------------------------- /动态规划/712.minimum-ascii-delete-sum-for-two-strings.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=712 lang=cpp 3 | * 4 | * [712] Minimum ASCII Delete Sum for Two Strings 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int minimumDeleteSum(string s1, string s2) { 11 | int n1 = s1.length(); 12 | int n2 = s2.length(); 13 | vector> dp(n1+1, vector(n2+1)); 14 | 15 | // 如果其中一个为空串,另一个需要全删 16 | // base case 17 | for (size_t i = 1; i < n1; i++) 18 | { 19 | dp[i][0] = dp[i-1][0] + s1[i-1]; 20 | } 21 | for (size_t i = 1; i < n2; i++) 22 | { 23 | dp[0][i] = dp[0][i-1] + s2[i-1]; 24 | } 25 | 26 | for (size_t i = 1; i < n1+1; i++) 27 | { 28 | for (size_t j = 1; j < n2+1; j++) 29 | { 30 | if (s1[i-1] == s2[j-1]) // 相等不需要删 31 | dp[i][j] = dp[i-1][j-1]; 32 | else 33 | // ? 不相等 选择小的那个删除 34 | dp[i][j] = min(dp[i-1][j] + s1[i-1], dp[i][j-1] + s2[j-1]); 35 | } 36 | } 37 | return dp[n1][n2]; 38 | } 39 | }; 40 | // @lc code=end 41 | 42 | -------------------------------------------------------------------------------- /动态规划/887.super-egg-drop.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=887 lang=cpp 3 | * 4 | * [887] Super Egg Drop 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int superEggDrop(int k, int n) { 11 | return dp(k, 1, n); 12 | } 13 | 14 | 15 | int dp(int k, int low, int hight) { 16 | if (k == 1) // 没有鸡蛋了 17 | return hight - low + 1; 18 | if (hight <= low) // 最后一层楼 19 | return 1; 20 | string key = to_string(k) + "," + to_string(hight - low + 1); 21 | if (memo.find(key) != memo.end()) 22 | { 23 | return memo[key]; 24 | } 25 | 26 | int res = INT_MAX; 27 | for (int i = low; i < hight + 1; i++) 28 | { 29 | int a = max(dp(k, i+1, hight), dp(k-1, low, i-1)) + 1; 30 | res = min(res, a); 31 | } 32 | memo[key] = res; 33 | return res; 34 | } 35 | 36 | private: 37 | unordered_map memo; 38 | }; 39 | // @lc code=end 40 | 41 | -------------------------------------------------------------------------------- /动态规划/91.decode-ways.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=91 lang=cpp 3 | * 4 | * [91] Decode Ways 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int numDecodings(string s) { 11 | int n = s.length(); 12 | if (n <= 0) 13 | return 0; 14 | vector dp(n+1); 15 | dp[0] = 1; 16 | dp[1] = s[0] == '0' ? 0 : 1; 17 | 18 | // dp表 以 i 为结尾能被解码的数量 19 | for (size_t i = 1; i < n; i++) 20 | { 21 | dp[i+1] = s[i] == '0' ? 0 : dp[i]; // 当前数字不为0,至少保证dp[i]种 22 | if (s[i-1] == '1' || s[i-1] == '2' && s[i] < '7') 23 | { 24 | dp[i+1] += dp[i-1]; 25 | } 26 | } 27 | return dp[n]; 28 | } 29 | }; 30 | // @lc code=end 31 | 32 | -------------------------------------------------------------------------------- /动态规划/91.decode-ways.py: -------------------------------------------------------------------------------- 1 | # 2 | # @lc app=leetcode id=91 lang=python3 3 | # 4 | # [91] Decode Ways 5 | # 6 | 7 | # @lc code=start 8 | class Solution: 9 | def numDecodings(self, s: str) -> int: 10 | n = len(s) 11 | dp = int[n+1] 12 | dp[0] = 1 13 | dp[1] = 0 if s[0] == '0' else 1 14 | for i in range(1, n+1): 15 | pass 16 | return dp[n] 17 | # @lc code=end 18 | 19 | -------------------------------------------------------------------------------- /单调栈/496.下一个更大元素-i.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=496 lang=cpp 3 | * 4 | * [496] 下一个更大元素 I 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector nextGreaterElement(vector& nums1, vector& nums2) { 11 | unordered_map table; // ni value : 比 ni大的下一个元素是 value 12 | stack st; // 单调栈 13 | vector res = vector(nums1.size(), -1); 14 | for (int i = 0; i < nums2.size(); i++) 15 | { 16 | while (!st.empty() && nums2[i] > st.top()) 17 | { 18 | table[st.top()] = nums2[i]; 19 | st.pop(); 20 | } 21 | st.push(nums2[i]); 22 | } 23 | for (int i = 0; i < nums1.size(); i++) 24 | { 25 | int n1 = nums1[i]; 26 | if (table.find(n1) != table.end()) 27 | res[i] = table[n1]; 28 | } 29 | return res; 30 | } 31 | }; 32 | // @lc code=end 33 | 34 | -------------------------------------------------------------------------------- /单调栈/503.下一个更大元素-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=503 lang=cpp 3 | * 4 | * [503] 下一个更大元素 II 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector nextGreaterElements(vector& nums) { 11 | // 1. 把 nums 后拼接 nums 模拟循环 12 | // 2. 使用 i % nums 13 | int n = nums.size(); 14 | vector res(n, -1); 15 | stack st; 16 | for (int i = 0; i < n * 2; i++) 17 | { 18 | while (!st.empty() && nums[i % n] > nums[st.top()]) 19 | { 20 | res[st.top()] = nums[i % n]; 21 | st.pop(); 22 | } 23 | st.push(i % n); 24 | } 25 | return res; 26 | } 27 | }; 28 | // @lc code=end 29 | 30 | -------------------------------------------------------------------------------- /单调栈/739.每日温度.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=739 lang=cpp 3 | * 4 | * [739] 每日温度 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector dailyTemperatures(vector& temperatures) { 11 | stack st; 12 | vector res(temperatures.size(), 0); 13 | for (int i = 0; i < temperatures.size(); i++) 14 | { 15 | while (!st.empty() && temperatures[st.top()] < temperatures[i]) 16 | { 17 | res[st.top()] = i - st.top(); 18 | st.pop(); 19 | } 20 | st.push(i); 21 | } 22 | return res; 23 | } 24 | 25 | }; 26 | // @lc code=end 27 | 28 | -------------------------------------------------------------------------------- /双指针/1089.复写零.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=1089 lang=cpp 3 | * 4 | * [1089] 复写零 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | // void duplicateZeros(vector& arr) { 11 | // vector a(arr); 12 | // int idx = 0; 13 | // for (int i = 0; i < a.size() - 1; i++) { 14 | // if (idx >= arr.size()) break; 15 | // if (a[i] == 0) { 16 | // arr[idx++] = 0; 17 | // if (idx >= arr.size()) break; 18 | // } 19 | // arr[idx++] = a[i]; 20 | // } 21 | // } 22 | 23 | void duplicateZeros(vector& arr) { 24 | int j = 0; 25 | for (int i = 0; j < arr.size(); i++) { 26 | if ((arr[i] & 0x0f) == 0) { 27 | j += 2; // 0 - 9 高4位为0 不用操作 28 | } else { 29 | arr[j++] |= ((arr[i] & 0x0f) << 4); // 低四位为arr[i]原来的值 30 | } 31 | } 32 | for (int i = 0; i < arr.size(); i++) { 33 | arr[i] = (arr[i] >> 4); 34 | } 35 | } 36 | }; 37 | // @lc code=end 38 | 39 | -------------------------------------------------------------------------------- /双指针/125.验证回文串.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=125 lang=cpp 3 | * 4 | * [125] 验证回文串 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | bool isPalindrome(string s) { 11 | vector ss; 12 | for (auto c: s) 13 | { 14 | if (c >= 'a' && c <= 'z' || c >= '0' && c <= '9') 15 | ss.push_back(c); 16 | else if (c >= 'A' && c <= 'Z') 17 | ss.push_back('a' + c - 'A'); 18 | } 19 | int i = 0; 20 | int j = ss.size() - 1; 21 | while (i < j) 22 | { 23 | // cout << ss[i] << " " << ss[j]; 24 | if (ss[i++] != ss[j--]) 25 | return false; 26 | } 27 | return true; 28 | } 29 | }; 30 | // @lc code=end 31 | 32 | -------------------------------------------------------------------------------- /双指针/1332.删除回文子序列.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=1332 lang=cpp 3 | * 4 | * [1332] 删除回文子序列 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int removePalindromeSub(string s) { 11 | // 因为只有 'a' 'b' 12 | // 所以最多只需要删除 2 次, 一次删除所有的 'a', 一次删除所有的 'b' 13 | if (s.size() == 0) 14 | return 0; 15 | int i = 0; 16 | int j = s.size() - 1; 17 | while (i < j) { 18 | if (s[i] != s[j]) { 19 | return 2; 20 | } 21 | i++; 22 | j--; 23 | } 24 | return 1; 25 | } 26 | }; 27 | // @lc code=end 28 | 29 | -------------------------------------------------------------------------------- /双指针/1385.两个数组间的距离值.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=1385 lang=cpp 3 | * 4 | * [1385] 两个数组间的距离值 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int findTheDistanceValue(vector& arr1, vector& arr2, int d) { 11 | sort(arr2.begin(), arr2.end()); 12 | 13 | int cnt = 0; 14 | // | a - b | <= d 15 | // -d <= a - b <= d 16 | // a - d <= b <= a + d 17 | for (int a : arr1) { 18 | auto it1 = lower_bound(arr2.begin(), arr2.end(), a - d); 19 | auto it2 = upper_bound(arr2.begin(), arr2.end(), a + d); 20 | // cout << *it1 << " " << *it2 << endl; 21 | if (it1 < it2) continue; 22 | cnt++; 23 | } 24 | return cnt; 25 | } 26 | }; 27 | // @lc code=end 28 | 29 | -------------------------------------------------------------------------------- /双指针/189.轮转数组.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=189 lang=cpp 3 | * 4 | * [189] 轮转数组 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | void rotate(vector& nums, int k) { 11 | int idx = k % nums.size(); 12 | vector temp(nums); 13 | for (int i = 0; i < temp.size(); i++) { 14 | nums[idx] = temp[i]; 15 | idx = (idx + 1) % temp.size(); 16 | } 17 | } 18 | }; 19 | // @lc code=end 20 | 21 | -------------------------------------------------------------------------------- /双指针/209.长度最小的子数组.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=209 lang=cpp 3 | * 4 | * [209] 长度最小的子数组 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int minSubArrayLen(int target, vector& nums) { 11 | // 滑动窗口 12 | int ans = INT_MAX; 13 | int i = 0; 14 | int j = 0; 15 | int sum = 0; 16 | while (j < nums.size()) { 17 | sum += nums[j]; 18 | ++j; 19 | while (sum >= target) 20 | { 21 | ans = min(ans, j - i); 22 | sum -= nums[i]; 23 | i++; 24 | } 25 | } 26 | return ans == INT_MAX ? 0 : ans; 27 | } 28 | }; 29 | // @lc code=end 30 | 31 | -------------------------------------------------------------------------------- /双指针/283.移动零.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=283 lang=cpp 3 | * 4 | * [283] 移动零 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | void moveZeroes(vector& nums) { 11 | int idx = 0; 12 | for (auto c : nums) { 13 | if (c != 0) 14 | nums[idx++] = c; 15 | } 16 | for (;idx < nums.size(); idx++) 17 | nums[idx] = 0; 18 | } 19 | }; 20 | // @lc code=end 21 | 22 | -------------------------------------------------------------------------------- /双指针/287.寻找重复数.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=287 lang=cpp 3 | * 4 | * [287] 寻找重复数 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int findDuplicate(vector& nums) { 11 | // 本题为求环形链表的入口 数组形式题 12 | // 快慢指针 13 | int slow = 0; 14 | int fast = 0; 15 | while (slow != fast || slow == 0) 16 | { 17 | slow = nums[slow]; 18 | fast = nums[nums[fast]]; 19 | } 20 | slow = 0; 21 | while (slow != fast) 22 | { 23 | slow = nums[slow]; 24 | fast = nums[fast]; 25 | } 26 | return fast; 27 | 28 | } 29 | }; 30 | // @lc code=end 31 | 32 | -------------------------------------------------------------------------------- /双指针/331.验证二叉树的前序序列化.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=331 lang=cpp 3 | * 4 | * [331] 验证二叉树的前序序列化 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | bool isValidSerialization(string preorder) { 11 | 12 | } 13 | }; 14 | // @lc code=end 15 | 16 | -------------------------------------------------------------------------------- /双指针/344.反转字符串.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=344 lang=cpp 3 | * 4 | * [344] 反转字符串 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | void reverseString(vector& s) { 11 | int i = 0; 12 | int j = s.size() - 1; 13 | char c; 14 | while (i < j) { 15 | c = s[i]; 16 | s[i] = s[j]; 17 | s[j] = c; 18 | i++; 19 | j--; 20 | } 21 | } 22 | }; 23 | // @lc code=end 24 | 25 | -------------------------------------------------------------------------------- /双指针/345.反转字符串中的元音字母.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=345 lang=cpp 3 | * 4 | * [345] 反转字符串中的元音字母 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | string reverseVowels(string s) { 11 | int i = 0; 12 | int j = s.size() - 1; 13 | char c; 14 | while (i < j) 15 | { 16 | while (!isYuanyin(s[i]) && i < j) 17 | i++; 18 | while (!isYuanyin(s[j]) && i < j) 19 | j--; 20 | if (i < j) 21 | { 22 | c = s[i]; 23 | s[i] = s[j]; 24 | s[j] = c; 25 | } 26 | i++; 27 | j--; 28 | } 29 | return s; 30 | } 31 | 32 | bool isYuanyin(char c) { 33 | return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' 34 | || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'; 35 | } 36 | }; 37 | // @lc code=end 38 | 39 | -------------------------------------------------------------------------------- /双指针/350.两个数组的交集-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=350 lang=cpp 3 | * 4 | * [350] 两个数组的交集 II 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector intersect(vector& nums1, vector& nums2) { 11 | unordered_map map1; 12 | unordered_map map2; 13 | for (auto c: nums1) 14 | map1[c]++; 15 | for (auto c: nums2) 16 | map2[c]++; 17 | vector ans; 18 | for (auto iter = map1.begin(); iter != map1.end(); ++iter) 19 | { 20 | int key = iter->first; 21 | if (map2[key] > 0) { 22 | int n = min(map1[key], map2[key]); 23 | for (int j = 0; j < n; j++) 24 | ans.push_back(key); 25 | } 26 | } 27 | return ans; 28 | } 29 | }; 30 | // @lc code=end 31 | 32 | -------------------------------------------------------------------------------- /双指针/392.判断子序列.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=392 lang=cpp 3 | * 4 | * [392] 判断子序列 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | bool isSubsequence(string s, string t) { 11 | int j = 0; 12 | for (char c : s) { 13 | while (j < t.size() && c != t[j]) 14 | j++; 15 | if (j >= t.size()) 16 | return false; 17 | j++; 18 | } 19 | return true; 20 | } 21 | }; 22 | // @lc code=end 23 | 24 | -------------------------------------------------------------------------------- /双指针/475.供暖器.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=475 lang=cpp 3 | * 4 | * [475] 供暖器 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int findRadius(vector& houses, vector& heaters) { 11 | // 1. 对于每个房屋,要么用前面的暖气,要么用后面的,二者取近的,得到距离; 12 | // 2. 对于所有的房屋,选择最大的上述距离。 13 | sort(houses.begin(), houses.end()); 14 | sort(heaters.begin(), heaters.end()); 15 | int radius = 0; 16 | int cur = 0; 17 | for (int h : houses) { 18 | while (cur < heaters.size() - 1 && abs(heaters[cur] - h) >= abs(heaters[cur + 1] - h)) 19 | cur++; 20 | radius = max(radius, abs(heaters[cur] - h)); 21 | } 22 | return radius; 23 | } 24 | }; 25 | // @lc code=end 26 | 27 | -------------------------------------------------------------------------------- /双指针/524.通过删除字母匹配到字典里最长单词.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=524 lang=cpp 3 | * 4 | * [524] 通过删除字母匹配到字典里最长单词 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | string findLongestWord(string s, vector& dictionary) { 11 | string ans = ""; 12 | sort(dictionary.begin(), dictionary.end(), [](string& s1, string& s2) -> bool { 13 | if (s1.size() == s2.size()) { 14 | return s1 < s2; 15 | } 16 | return s1.size() > s2.size(); 17 | }); 18 | for (string& d : dictionary) { 19 | if (isSubseq(s, d)) { 20 | return d; 21 | } 22 | } 23 | return ""; 24 | } 25 | 26 | 27 | bool isSubseq(const string& src, const string& sub) { 28 | int i = 0; 29 | int j = 0; 30 | while (i < src.size() && j < sub.size()) { 31 | if (src[i] == sub[j]) 32 | j++; 33 | i++; 34 | } 35 | return j >= sub.size(); 36 | } 37 | }; 38 | // @lc code=end 39 | 40 | -------------------------------------------------------------------------------- /双指针/532.数组中的-k-diff-数对.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=532 lang=cpp 3 | * 4 | * [532] 数组中的 k-diff 数对 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int findPairs(vector& nums, int k) { 11 | sort(nums.begin(), nums.end()); 12 | unordered_set memo; 13 | unordered_set ans; 14 | for (auto c : nums) { 15 | if (memo.find(c - k) != memo.end()) 16 | ans.insert(c); 17 | if (memo.find(c + k) != memo.end()) 18 | ans.insert(c); 19 | memo.insert(c); 20 | } 21 | return ans.size(); 22 | } 23 | }; 24 | // @lc code=end 25 | 26 | -------------------------------------------------------------------------------- /双指针/541.reverse-string-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=541 lang=cpp 3 | * 4 | * [541] Reverse String II 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | string reverseStr(string s, int k) { 11 | int left = 0; 12 | int right = 0; 13 | int n = s.size(); 14 | while (left < n) { 15 | right = min(n - 1, left + k - 1); 16 | reverse(s, left, right); 17 | left = left + 2 * k; 18 | } 19 | return s; 20 | } 21 | void reverse(string& s, int left, int right) { 22 | while (left < right) { 23 | char c = s[left]; 24 | s[left] = s[right]; 25 | s[right] = c; 26 | left++; 27 | right--; 28 | } 29 | } 30 | }; 31 | // @lc code=end 32 | 33 | -------------------------------------------------------------------------------- /双指针/557.reverse-words-in-a-string-iii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=557 lang=cpp 3 | * 4 | * [557] Reverse Words in a String III 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | string reverseWords(string s) { 11 | // reverse(s, 0, s.size() - 1); 12 | int left = 0; 13 | int right = 0; 14 | while (left < s.size()) { 15 | while (right < s.size() && s[right] != ' ') 16 | right++; 17 | // cout << right << "/" << s.size() << " "; 18 | reverse(s, left, right - 1); 19 | // cout << "22/" << " " << endl; 20 | left = right = right + 1; 21 | } 22 | return s; 23 | } 24 | 25 | void reverse(string& s, int left, int right) { 26 | while (left < right) { 27 | char c = s[left]; 28 | s[left] = s[right]; 29 | s[right] = c; 30 | left++; 31 | right--; 32 | } 33 | } 34 | }; 35 | // @lc code=end 36 | 37 | -------------------------------------------------------------------------------- /双指针/567.permutation-in-string.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=567 lang=cpp 3 | * 4 | * [567] Permutation in String 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | bool checkInclusion(string s1, string s2) { 11 | if (s2.size() < s1.size()) return false; 12 | vector v1(26); 13 | vector v2(26); 14 | // 滑动窗口 15 | int n = s1.size(); 16 | for (int i = 0; i < n; i++) { 17 | v1[s1[i] - 'a']++; 18 | v2[s2[i] - 'a']++; 19 | } 20 | if (v1 == v2) return true; 21 | for (int i = n; i < s2.size(); i++) { 22 | v2[s2[i - n] - 'a']--; 23 | v2[s2[i] - 'a']++; 24 | if (v1 == v2) return true; 25 | } 26 | return false; 27 | } 28 | }; 29 | // @lc code=end 30 | 31 | -------------------------------------------------------------------------------- /双指针/581.最短无序连续子数组.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=581 lang=cpp 3 | * 4 | * [581] 最短无序连续子数组 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | // TODO: 未完成 11 | int findUnsortedSubarray(vector& nums) { 12 | int left = 0; 13 | int right = 0; 14 | for (int i = 1; i < nums.size(); i++) { 15 | if (nums[i] < nums[i-1]) { 16 | left = i - 1; 17 | right = i; 18 | break; 19 | } 20 | } 21 | if (left == 0 && right == 0) 22 | return 0; 23 | cout << left << " " << right << endl; 24 | for (int i = right; i < nums.size(); i++) { 25 | cout << " i=" << i << endl;; 26 | if (nums[i] < nums[i - 1]) { 27 | // 处理重复 28 | while (i < nums.size() - 1 && nums[i + 1] == nums[i]) 29 | { 30 | i++; 31 | } 32 | right = i; 33 | } 34 | } 35 | 36 | return right - left + 1; 37 | } 38 | }; 39 | // @lc code=end 40 | 41 | -------------------------------------------------------------------------------- /双指针/611.有效三角形的个数.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=611 lang=cpp 3 | * 4 | * [611] 有效三角形的个数 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int triangleNumber(vector& nums) { 11 | int ans = 0; 12 | sort(nums.begin(), nums.end()); 13 | for (int i = 0; i < nums.size(); i++) { 14 | for (int j = i + 1; j < nums.size(); j++) { 15 | // 二分法搜索 16 | int left = j + 1; 17 | int right = nums.size() - 1; 18 | int b = j; 19 | while (left <= right) { 20 | int mid = left + (right - left) / 2; 21 | if (nums[mid] < nums[i] + nums[j]) { 22 | left = mid + 1; 23 | b = mid; 24 | } else { 25 | right = mid - 1; 26 | } 27 | } 28 | // cout << left << " " << right << " " << j << endl; 29 | ans += (b - j); 30 | } 31 | } 32 | return ans; 33 | } 34 | 35 | }; 36 | // @lc code=end 37 | 38 | -------------------------------------------------------------------------------- /双指针/633.平方数之和.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=633 lang=cpp 3 | * 4 | * [633] 平方数之和 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | bool judgeSquareSum(int c) { 11 | int sq = (int)sqrt(c); 12 | long a = 0; 13 | long b = sq; 14 | while (a <= b) { 15 | if (a * a + b * b < c) { 16 | a++; 17 | } else if (a * a + b * b > c) { 18 | b--; 19 | } else { 20 | return true; 21 | } 22 | } 23 | return false; 24 | } 25 | }; 26 | // @lc code=end 27 | 28 | -------------------------------------------------------------------------------- /双指针/658.找到-k-个最接近的元素.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=658 lang=cpp 3 | * 4 | * [658] 找到 K 个最接近的元素 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector findClosestElements(vector& arr, int k, int x) { 11 | priority_queue, less> hp; 12 | vector ans(k); 13 | // int s = INT_MAX; 14 | int prev = INT_MAX; 15 | int idx = 0; 16 | for (int i = 0; i < arr.size() - k + 1; i++) { 17 | int t = getSum(arr, i, k, x); 18 | if (t < prev) { 19 | idx = i; 20 | } 21 | else if (t > prev) { 22 | break; // 提前退出循环 23 | } 24 | prev = t; 25 | } 26 | 27 | for (int i = 0; i < k; i++) { 28 | ans[i] = arr[idx+i]; 29 | } 30 | return ans; 31 | } 32 | 33 | int getSum(const vector& arr, int idx, int k, int x) { 34 | int sum = 0; 35 | for (int i = 0; i < k; i++) { 36 | sum += abs(arr[i+idx] - x); 37 | } 38 | return sum; 39 | } 40 | }; 41 | // @lc code=end 42 | 43 | -------------------------------------------------------------------------------- /双指针/763.划分字母区间.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=763 lang=cpp 3 | * 4 | * [763] 划分字母区间 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector partitionLabels(string s) { 11 | unordered_map pos; // start end 12 | for (int i = 0; i < s.size(); i++) { 13 | char c = s[i]; 14 | pos[c] = i; 15 | } 16 | vector ans; 17 | int start = 0; 18 | int end = 0; 19 | for (int i = 0; i < s.size(); i++) { 20 | if (i <= end) { 21 | end = max(end, pos[s[i]]); 22 | } else { 23 | ans.push_back(end - start + 1); // 数量为下标 + 1 24 | start = end + 1; 25 | end = max(end, pos[s[i]]); 26 | } 27 | } 28 | ans.push_back(s.size() - start); 29 | return ans; 30 | } 31 | }; 32 | // @lc code=end 33 | 34 | -------------------------------------------------------------------------------- /双指针/795.区间子数组个数.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=795 lang=cpp 3 | * 4 | * [795] 区间子数组个数 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int numSubarrayBoundedMax(vector& nums, int left, int right) { 11 | int start = -1, temp = 0, ans = 0; 12 | for(int i = 0; i < nums.size(); i++) { 13 | if(nums[i] > right) 14 | start = i; 15 | if(nums[i] >= left) 16 | temp = i - start; 17 | ans += temp; 18 | } 19 | return ans; 20 | } 21 | }; 22 | // @lc code=end 23 | 24 | -------------------------------------------------------------------------------- /双指针/821.字符的最短距离.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=821 lang=cpp 3 | * 4 | * [821] 字符的最短距离 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector shortestToChar(string s, char c) { 11 | vector ans(s.size(), s.size()); 12 | int pos = -1; 13 | for (int i = 0; i < s.size(); i++) { 14 | if (s[i] == c) 15 | pos = i; 16 | if (pos != -1) { 17 | ans[i] = min(ans[i], i - pos); 18 | } 19 | } 20 | pos = s.size(); 21 | for (int i = s.size() - 1; i >= 0; i--) { 22 | if (s[i] == c) 23 | pos = i; 24 | if (pos != s.size()) { 25 | ans[i] = min(ans[i], pos - i); 26 | } 27 | } 28 | return ans; 29 | } 30 | }; 31 | // @lc code=end 32 | 33 | -------------------------------------------------------------------------------- /双指针/825.适龄的朋友.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=825 lang=cpp 3 | * 4 | * [825] 适龄的朋友 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int numFriendRequests(vector& ages) { 11 | int n = ages.size(); 12 | int ans = 0; 13 | int AM = 121; 14 | vector cnt(AM); 15 | for (int age : ages) { 16 | cnt[age]++; 17 | } 18 | vector pre(AM); 19 | pre[0] = cnt[0]; 20 | for (int i = 1; i < AM; i++) { 21 | pre[i] = pre[i-1] + cnt[i]; 22 | } 23 | for (int i = 15; i < AM; i++) { 24 | if (cnt[i] > 0) { 25 | int y = i * 0.5 + 7; 26 | ans = ans + cnt[i] * (pre[i] - pre[y] - 1); 27 | } 28 | } 29 | return ans; 30 | 31 | } 32 | }; 33 | // @lc code=end 34 | 35 | -------------------------------------------------------------------------------- /双指针/832.翻转图像.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=832 lang=cpp 3 | * 4 | * [832] 翻转图像 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector> flipAndInvertImage(vector>& image) { 11 | int n = image.size(); 12 | for (int i = 0; i < n; i++) { 13 | int n = image[i].size(); 14 | int left = 0; 15 | int right = n - 1; 16 | while (left <= right) { 17 | int t = image[i][left]; 18 | image[i][left] = !image[i][right]; 19 | image[i][right] = !t; 20 | left++; 21 | right--; 22 | } 23 | } 24 | return image; 25 | } 26 | }; 27 | // @lc code=end 28 | 29 | -------------------------------------------------------------------------------- /双指针/844.比较含退格的字符串.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=844 lang=cpp 3 | * 4 | * [844] 比较含退格的字符串 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | bool backspaceCompare(string s, string t) { 11 | int idx1 = 0; 12 | for (char c : s) { 13 | if (c == '#') 14 | idx1 = max(0, idx1 - 1); 15 | else 16 | s[idx1++] = c; 17 | } 18 | int idx2 = 0; 19 | for (char c : t) { 20 | if (c == '#') 21 | idx2 = max(0, idx2 - 1); 22 | else 23 | t[idx2++] = c; 24 | } 25 | return idx1 == idx2 && s.substr(0, idx1) == t.substr(0, idx2); 26 | } 27 | }; 28 | // @lc code=end 29 | 30 | -------------------------------------------------------------------------------- /双指针/922.按奇偶排序数组-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=922 lang=cpp 3 | * 4 | * [922] 按奇偶排序数组 II 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector sortArrayByParityII(vector& nums) { 11 | // 空间复杂度 O(1) 12 | int n = nums.size(); 13 | int odd = 1; 14 | int even = 0; 15 | while (even < n) { 16 | if (nums[even] % 2 == 1) { 17 | while (nums[odd] % 2 == 1) { 18 | odd += 2; 19 | } 20 | int t = nums[even]; 21 | nums[even] = nums[odd]; 22 | nums[odd] = t; 23 | odd += 2; 24 | } 25 | even += 2; 26 | } 27 | return nums; 28 | } 29 | }; 30 | // @lc code=end 31 | 32 | -------------------------------------------------------------------------------- /双指针/925.长按键入.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=925 lang=cpp 3 | * 4 | * [925] 长按键入 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | bool isLongPressedName(string name, string typed) { 11 | if (name[0] != typed[0]) return false; 12 | char pre = name[0]; 13 | int j = 1; 14 | for (int i = 1; i < name.size(); i++) { 15 | if (typed[j] == name[i]) { 16 | j++; 17 | } else { 18 | while (typed[j] == pre) 19 | j++; 20 | if (typed[j] != name[i]) { 21 | return false; 22 | } else { 23 | j++; 24 | } 25 | } 26 | pre = name[i]; 27 | } 28 | for (; j < typed.size(); j++) { 29 | if (typed[j] != pre) 30 | return false; 31 | } 32 | return true; 33 | } 34 | }; 35 | // @lc code=end 36 | 37 | -------------------------------------------------------------------------------- /双指针/977.有序数组的平方.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=977 lang=cpp 3 | * 4 | * [977] 有序数组的平方 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector sortedSquares(vector& nums) { 11 | int i = 0; 12 | int n = nums.size(); 13 | for (; i < nums.size() && nums[i] < 0; i++) ; 14 | int j = i - 1; 15 | vector ans(n); 16 | for (int k = 0; k < n; k++) { 17 | if (i >= n) { 18 | ans[k] = nums[j] * nums[j]; 19 | j--; 20 | } else if (j < 0) { 21 | ans[k] = nums[i] * nums[i]; 22 | i++; 23 | } else if (abs(nums[i]) < abs(nums[j])) { 24 | ans[k] = nums[i] * nums[i]; 25 | i++; 26 | } else { 27 | ans[k] = nums[j] * nums[j]; 28 | j--; 29 | } 30 | } 31 | return ans; 32 | } 33 | }; 34 | // @lc code=end 35 | 36 | -------------------------------------------------------------------------------- /哈希表/169.多数元素.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=169 lang=cpp 3 | * 4 | * [169] 多数元素 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int majorityElement(vector& nums) { 11 | unordered_map mm; 12 | int n = nums.size(); 13 | for (int c : nums) { 14 | mm[c]++; 15 | if (mm[c] > n / 2) 16 | return c; 17 | } 18 | return -1; 19 | } 20 | }; 21 | // @lc code=end 22 | 23 | -------------------------------------------------------------------------------- /哈希表/187.重复的dna序列.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=187 lang=cpp 3 | * 4 | * [187] 重复的DNA序列 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector findRepeatedDnaSequences(string s) { 11 | if (s.size() <= 10) return { }; 12 | unordered_set memo; 13 | unordered_set res; 14 | vector ans; 15 | for (int i = 0; i < s.size() - 9; i++) { 16 | string a = s.substr(i, 10); 17 | if (memo.find(a) != memo.end()) { 18 | res.insert(a); 19 | } 20 | memo.insert(a); 21 | } 22 | 23 | for (auto& item : res) { 24 | ans.push_back(item); 25 | } 26 | return ans; 27 | } 28 | }; 29 | // @lc code=end 30 | 31 | -------------------------------------------------------------------------------- /哈希表/202.快乐数.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=202 lang=cpp 3 | * 4 | * [202] 快乐数 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | bool isHappy(int n) { 11 | unordered_set s; 12 | vector table = { 0, 1, 4, 9, 16, 25, 36, 49, 64, 81}; 13 | int num = 0; 14 | s.insert(n); 15 | while (1) 16 | { 17 | while (n) 18 | { 19 | num += table[n % 10]; 20 | n = n / 10; 21 | } 22 | 23 | if (num == 1) 24 | return true; 25 | if (s.find(num) != s.end()) 26 | return false; 27 | n = num; 28 | num = 0; 29 | s.insert(n); 30 | } 31 | } 32 | }; 33 | // @lc code=end 34 | 35 | -------------------------------------------------------------------------------- /哈希表/204.计数质数.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=204 lang=cpp 3 | * 4 | * [204] 计数质数 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int countPrimes(int n) { 11 | vector isPrime(n, true); 12 | 13 | int ans = 0; 14 | for (int i = 2; i < n; i++) 15 | { 16 | if (isPrime[i]) { 17 | ans++; 18 | // i 的倍数都不是质数 19 | int m = 2; 20 | while (m * i < n) 21 | { 22 | isPrime[m*i] = false; 23 | m++; 24 | } 25 | } 26 | } 27 | return ans; 28 | 29 | } 30 | }; 31 | // @lc code=end 32 | 33 | -------------------------------------------------------------------------------- /哈希表/205.同构字符串.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=205 lang=cpp 3 | * 4 | * [205] 同构字符串 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | bool isIsomorphic(string s, string t) { 11 | if (s.size() != t.size()) return false; 12 | int n = s.size(); 13 | unordered_map map; 14 | unordered_set memo; 15 | for (int i = 0; i < n; i++) { 16 | if (map.find(s[i]) == map.end()) { 17 | // 已经被映射过了 18 | if (memo.find(t[i]) != memo.end()) 19 | return false; 20 | map[s[i]] = t[i]; 21 | memo.insert(t[i]); 22 | } else { 23 | if (map[s[i]] != t[i]) 24 | return false; 25 | } 26 | } 27 | return true; 28 | } 29 | }; 30 | // @lc code=end 31 | 32 | -------------------------------------------------------------------------------- /哈希表/217.存在重复元素.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=217 lang=cpp 3 | * 4 | * [217] 存在重复元素 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | bool containsDuplicate(vector& nums) { 11 | unordered_set st; 12 | for (int a : nums) { 13 | if (st.find(a) != st.end()) 14 | return true; 15 | st.insert(a); 16 | } 17 | return false; 18 | } 19 | }; 20 | // @lc code=end 21 | 22 | -------------------------------------------------------------------------------- /哈希表/219.存在重复元素-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=219 lang=cpp 3 | * 4 | * [219] 存在重复元素 II 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | bool containsNearbyDuplicate(vector& nums, int k) { 11 | unordered_map map; 12 | for (int i = 0; i < nums.size(); i++) { 13 | if (map.find(nums[i]) != map.end() && abs(i - map[nums[i]]) <= k) 14 | return true; 15 | map[nums[i]] = i; 16 | } 17 | return false; 18 | } 19 | }; 20 | // @lc code=end 21 | 22 | -------------------------------------------------------------------------------- /哈希表/242.有效的字母异位词.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=242 lang=cpp 3 | * 4 | * [242] 有效的字母异位词 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | bool isAnagram(string s, string t) { 11 | if (s.size() != t.size()) 12 | return false; 13 | vector table(26); // 只有小写字母 14 | for (int i = 0; i < s.size(); i++) 15 | { 16 | table[s[i] - 'a'] += 1; 17 | } 18 | for (int i = 0; i < t.size(); i++) 19 | { 20 | if (table[t[i] - 'a'] <= 0) 21 | return false; 22 | table[t[i] - 'a'] -= 1; 23 | } 24 | 25 | return true; 26 | } 27 | }; 28 | // @lc code=end 29 | 30 | -------------------------------------------------------------------------------- /哈希表/274.h-指数.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=274 lang=cpp 3 | * 4 | * [274] H 指数 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int hIndex(vector& citations) { 11 | sort(citations.begin(), citations.end()); 12 | int m = citations.size(); 13 | int left = 0; 14 | int right = m - 1; 15 | while (left < right) 16 | { 17 | int mid = left + (right - left) / 2; 18 | if (citations[mid] >= (m - mid)) { 19 | right = mid; 20 | } else { 21 | left = mid + 1; 22 | } 23 | } 24 | if (citations[right] == 0) return 0; // testcase: [0] 25 | return m - right; 26 | } 27 | }; 28 | // @lc code=end 29 | 30 | -------------------------------------------------------------------------------- /哈希表/299.猜数字游戏.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=299 lang=cpp 3 | * 4 | * [299] 猜数字游戏 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | string getHint(string secret, string guess) { 11 | // 数字对了 - 数字和位置全对了 12 | // 1. 数字 位置全对了 13 | int count1 = 0; 14 | // 2. 数字对了,不论顺序 15 | int count2 = 0; 16 | vector m1(10); 17 | vector m2(10); 18 | int n = secret.size(); 19 | for (int i = 0; i < n; i++) { 20 | if (secret[i] == guess[i]) 21 | { 22 | count1++; 23 | } 24 | m1[secret[i] - '0']++; 25 | m2[guess[i] - '0']++; 26 | } 27 | for (size_t i = 0; i < 10; i++) 28 | { 29 | count2 += min(m1[i], m2[i]); 30 | } 31 | stringstream oss; 32 | oss << count1 << "A" << count2 - count1 << "B"; 33 | return oss.str(); 34 | } 35 | }; 36 | // @lc code=end 37 | 38 | -------------------------------------------------------------------------------- /哈希表/349.两个数组的交集.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=349 lang=cpp 3 | * 4 | * [349] 两个数组的交集 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector intersection(vector& nums1, vector& nums2) { 11 | int MAX_ITEM = 1000; 12 | unordered_set result_set; 13 | vector table(MAX_ITEM + 1, false); 14 | for (size_t i = 0; i < nums1.size(); i++) 15 | { 16 | table[nums1[i]] = true; 17 | } 18 | for (size_t i = 0; i < nums2.size(); i++) 19 | { 20 | if (table[nums2[i]]) 21 | { 22 | result_set.insert(nums2[i]); 23 | } 24 | 25 | } 26 | return vector(result_set.begin(), result_set.end()); 27 | } 28 | }; 29 | // @lc code=end 30 | 31 | -------------------------------------------------------------------------------- /哈希表/383.赎金信.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=383 lang=cpp 3 | * 4 | * [383] 赎金信 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | bool canConstruct(string ransomNote, string magazine) { 11 | if (ransomNote.size() > magazine.size()) 12 | return false; 13 | vector table(26); 14 | for (char c : magazine) 15 | { 16 | table[c - 'a'] += 1; 17 | } 18 | for (char c : ransomNote) 19 | { 20 | if (table[c - 'a'] <= 0) 21 | return false; 22 | table[c - 'a'] -= 1; 23 | } 24 | return true; 25 | } 26 | }; 27 | // @lc code=end 28 | 29 | -------------------------------------------------------------------------------- /哈希表/387.字符串中的第一个唯一字符.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=387 lang=cpp 3 | * 4 | * [387] 字符串中的第一个唯一字符 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int firstUniqChar(string s) { 11 | vector memo(255); 12 | for (char c : s) { 13 | memo[c]++; 14 | } 15 | for (int i = 0; i < s.size(); i++) { 16 | if (memo[s[i]] == 1) { 17 | return i; 18 | } 19 | } 20 | return -1; 21 | } 22 | }; 23 | // @lc code=end 24 | 25 | -------------------------------------------------------------------------------- /哈希表/389.找不同.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=389 lang=cpp 3 | * 4 | * [389] 找不同 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | char findTheDifference(string s, string t) { 11 | char ans = 0; 12 | for (char c : s) { 13 | ans = ans ^ c; 14 | } 15 | for (char c : t) { 16 | ans = ans ^ c; 17 | } 18 | return ans; 19 | } 20 | }; 21 | // @lc code=end 22 | 23 | -------------------------------------------------------------------------------- /哈希表/409.最长回文串.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=409 lang=cpp 3 | * 4 | * [409] 最长回文串 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int longestPalindrome(string s) { 11 | // 双数一定能构造 12 | // 只能有一个单数 13 | int odd = 0; 14 | int ans = 0; 15 | unordered_map memo; 16 | for (char c: s) { 17 | memo[c]++; 18 | } 19 | for (auto& kv : memo) { 20 | if (kv.second % 2 == 0) { 21 | ans += kv.second; 22 | } else { 23 | odd = 1; 24 | ans += kv.second - 1; 25 | } 26 | } 27 | return ans + odd; 28 | } 29 | }; 30 | // @lc code=end 31 | 32 | -------------------------------------------------------------------------------- /哈希表/438.找到字符串中所有字母异位词.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=438 lang=cpp 3 | * 4 | * [438] 找到字符串中所有字母异位词 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector findAnagrams(string s, string p) { 11 | if (s.size() < p.size()) return {}; 12 | int k = p.size(); 13 | vector mp(256); 14 | vector ms(256); 15 | for (int i = 0; i < k; i++) { 16 | mp[p[i]]++; 17 | ms[s[i]]++; 18 | } 19 | vector ans; 20 | if (mp == ms) ans.push_back(0); 21 | // 滑动窗口 22 | for (int i = k; i < s.size(); i++) { 23 | // 丢弃一个 24 | ms[s[i-k]]--; 25 | // 加入一个 26 | ms[s[i]]++; 27 | if (mp == ms) ans.push_back(i-k+1); 28 | } 29 | return ans; 30 | } 31 | }; 32 | // @lc code=end 33 | 34 | -------------------------------------------------------------------------------- /哈希表/451.根据字符出现频率排序.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=451 lang=cpp 3 | * 4 | * [451] 根据字符出现频率排序 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | string frequencySort(string s) { 11 | vector counting(256); 12 | for (char c : s) { 13 | counting[c]++; 14 | } 15 | string ans; 16 | while (ans.size() < s.size()) { 17 | int max_idx = 0; 18 | for (size_t i = 0; i < counting.size(); i++) { 19 | if (counting[i] > counting[max_idx]) { 20 | max_idx = i; 21 | } 22 | } 23 | ans += string(counting[max_idx], max_idx); 24 | counting[max_idx] = 0; 25 | } 26 | return ans; 27 | } 28 | }; 29 | // @lc code=end 30 | 31 | -------------------------------------------------------------------------------- /哈希表/454.四数相加-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=454 lang=cpp 3 | * 4 | * [454] 四数相加 II 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int fourSumCount(vector& nums1, vector& nums2, vector& nums3, vector& nums4) { 11 | unordered_map m; 12 | for (int a : nums1) 13 | { 14 | for (int b : nums2) 15 | { 16 | m[a + b]++; 17 | } 18 | } 19 | int res = 0; 20 | 21 | for (int c : nums3) 22 | { 23 | for (int d : nums4) 24 | { 25 | res += m[0 - (c + d)]; 26 | } 27 | } 28 | return res; 29 | } 30 | }; 31 | // @lc code=end 32 | 33 | -------------------------------------------------------------------------------- /哈希表/49.字母异位词分组.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=49 lang=cpp 3 | * 4 | * [49] 字母异位词分组 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector> groupAnagrams(vector& strs) { 11 | unordered_map> m; 12 | for(int i = 0; i < strs.size(); i++) 13 | { 14 | string s(strs[i]); 15 | sort(s.begin(), s.end()); 16 | m[s].push_back(strs[i]); 17 | } 18 | vector> ans; 19 | for (auto iter = m.begin(); iter != m.end(); ++iter) 20 | { 21 | ans.push_back(iter->second); 22 | } 23 | return ans; 24 | } 25 | }; 26 | // @lc code=end 27 | 28 | -------------------------------------------------------------------------------- /哈希表/554.砖墙.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=554 lang=cpp 3 | * 4 | * [554] 砖墙 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int leastBricks(vector>& wall) { 11 | // 统计边界的最大个数 12 | unordered_map bound; 13 | for (const vector& v : wall) 14 | { 15 | int x = 0; 16 | for (int i = 0; i < v.size() - 1; i++) { 17 | x += v[i]; 18 | bound[x]++; 19 | } 20 | } 21 | int res = 0; 22 | for (auto& kv : bound) { 23 | res = max(res, kv.second); 24 | } 25 | return wall.size() - res; 26 | } 27 | }; 28 | // @lc code=end 29 | 30 | -------------------------------------------------------------------------------- /哈希表/575.分糖果.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=575 lang=cpp 3 | * 4 | * [575] 分糖果 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int distributeCandies(vector& candyType) { 11 | unordered_set memo; 12 | for (int c : candyType) { 13 | memo[c]++; 14 | } 15 | return min(candyType.size() / 2, memo.size()); 16 | } 17 | }; 18 | // @lc code=end 19 | 20 | -------------------------------------------------------------------------------- /哈希表/594.最长和谐子序列.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=594 lang=cpp 3 | * 4 | * [594] 最长和谐子序列 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int findLHS(vector& nums) { 11 | int ans = 0; 12 | unordered_map memo; // 统计个数 13 | for (int i = 0; i < nums.size(); i++) { 14 | memo[nums[i]]++; 15 | } 16 | // 子序列只能包含 a, a+1 或 a-1, a 17 | for (auto& kv : memo) { 18 | int key = kv.first; 19 | // key+1 不存在于 memo时, 20 | // 使用 memo[key+1]这种写法会初始化 memo[key+1] = 0, 影响for循环对memo的遍历 21 | if (memo.find(key+1) != memo.end()) 22 | ans = max(ans, memo[key] + memo[key+1]); 23 | if (memo.find(key-1) != memo.end()) 24 | ans = max(ans, memo[key] + memo[key-1]); 25 | } 26 | return ans; 27 | } 28 | }; 29 | // @lc code=end 30 | 31 | -------------------------------------------------------------------------------- /哈希表/599.两个列表的最小索引总和.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=599 lang=cpp 3 | * 4 | * [599] 两个列表的最小索引总和 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector findRestaurant(vector& list1, vector& list2) { 11 | unordered_map map1; 12 | unordered_map map2; 13 | for (size_t i = 0; i < list1.size(); i++) { 14 | map1[list1[i]] = i; 15 | } 16 | for (size_t i = 0; i < list2.size(); i++) { 17 | map2[list2[i]] = i; 18 | } 19 | vector ans; 20 | int sum = INT_MAX; 21 | for (auto& kv : map2) { 22 | string k = kv.first; 23 | if (map1.find(k) != map1.end()) { 24 | if (map1[k] + map2[k] < sum) { 25 | ans.clear(); 26 | ans.push_back(k); 27 | sum = map1[k] + map2[k]; 28 | } else if (map1[k] + map2[k] == sum) { 29 | ans.push_back(k); 30 | } 31 | } 32 | } 33 | return ans; 34 | } 35 | }; 36 | // @lc code=end 37 | 38 | -------------------------------------------------------------------------------- /回溯法/1541.minimum-insertions-to-balance-a-parentheses-string.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1541 lang=cpp 3 | * 4 | * [1541] Minimum Insertions to Balance a Parentheses String 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int minInsertions(string s) { 11 | int count = 0; 12 | int right = 0; 13 | for (int i = 0; i < s.size(); i++) 14 | { 15 | if (s[i] == '(') 16 | { 17 | if (right % 2 != 0) // 奇数 不配对 18 | { 19 | right -= 1; 20 | count++; // 有插入操作 21 | } 22 | 23 | right += 2; 24 | } 25 | if (s[i] == ')') 26 | { 27 | right -= 1; 28 | if (right == -1) // 右括号太多 这里不能为 -2 因为 ')(' 这种情况会在 -1 时 right + 2 导致忽略 ')' 29 | { 30 | count += 1; // 有插入操作 31 | right = 1; 32 | } 33 | 34 | } 35 | } 36 | return count + right; 37 | } 38 | }; 39 | // @lc code=end 40 | 41 | -------------------------------------------------------------------------------- /回溯法/20.valid-parentheses.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=20 lang=cpp 3 | * 4 | * [20] Valid Parentheses 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | bool isValid(string s) { 11 | stack stk; 12 | for (int i = 0; i < s.length(); i++) 13 | { 14 | if (s[i] == '(' || s[i] == '[' || s[i] == '{') 15 | { 16 | stk.push(s[i]); 17 | } 18 | else 19 | { 20 | if (stk.empty()) 21 | { 22 | return false; 23 | } 24 | 25 | if (s[i] == ')' && stk.top() != '(' 26 | || s[i] == ']' && stk.top() != '[' 27 | || s[i] == '}' && stk.top() != '{') 28 | { 29 | return false; 30 | } 31 | stk.pop(); 32 | } 33 | } 34 | return stk.empty(); 35 | } 36 | }; 37 | // @lc code=end 38 | 39 | -------------------------------------------------------------------------------- /回溯法/39.combination-sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=39 lang=cpp 3 | * 4 | * [39] Combination Sum 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector> combinationSum(vector& candidates, int target) { 11 | vector sub; 12 | backtrack(candidates, target, sub, 0, 0); 13 | return res; 14 | } 15 | 16 | void backtrack(const vector& candidates, int target, vector& sub, int left, int sum) 17 | { 18 | if (sum == target) 19 | { 20 | res.push_back(sub); 21 | return; 22 | } 23 | for (int i = left; i < candidates.size(); i++) 24 | { 25 | int val = candidates[i]; 26 | if (sum + val > target) 27 | { 28 | continue; 29 | } 30 | sum += val; 31 | sub.push_back(val); 32 | backtrack(candidates, target, sub, i, sum); 33 | sub.pop_back(); 34 | sum -= val; 35 | } 36 | 37 | } 38 | 39 | private: 40 | vector> res; 41 | }; 42 | // @lc code=end 43 | 44 | -------------------------------------------------------------------------------- /回溯法/46.permutations.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=46 lang=cpp 3 | * 4 | * [46] Permutations 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector> permute(vector& nums) { 11 | vector a; 12 | backtrack(nums, 0, a); 13 | return res; 14 | } 15 | 16 | void backtrack(const vector& nums, int left, vector& sub) 17 | { 18 | if (sub.size() == nums.size()) 19 | { 20 | res.push_back(sub); 21 | return; 22 | } 23 | for (int i = 0; i < nums.size(); i++) 24 | { 25 | if (find(sub.begin(), sub.end(), nums[i]) != sub.end()) 26 | { 27 | continue; 28 | } 29 | 30 | sub.push_back(nums[i]); 31 | backtrack(nums, i + 1, sub); 32 | sub.pop_back(); 33 | } 34 | 35 | } 36 | 37 | private: 38 | vector> res; 39 | }; 40 | // @lc code=end 41 | 42 | -------------------------------------------------------------------------------- /回溯法/47.全排列-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=47 lang=cpp 3 | * 4 | * [47] 全排列 II 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector> permuteUnique(vector& nums) { 11 | sort(nums.begin(), nums.end()); 12 | vector temp(nums.size()); 13 | vector visited(nums.size(), false); 14 | traceback(nums, 0, visited, temp); 15 | return ans; 16 | } 17 | 18 | private: 19 | void traceback(const vector& nums, int idx, vector& visited, vector& temp) 20 | { 21 | if (idx == nums.size()) 22 | { 23 | ans.push_back(temp); 24 | return; 25 | } 26 | 27 | for (int i = 0; i < nums.size(); i++) 28 | { 29 | if (visited[i] || i > 0 && nums[i] == nums[i-1] && !visited[i-1]) 30 | continue; 31 | visited[i] = true; 32 | temp[idx] = nums[i]; 33 | traceback(nums, idx + 1, visited, temp); 34 | visited[i] = false; 35 | } 36 | } 37 | 38 | vector> ans; 39 | }; 40 | // @lc code=end 41 | 42 | -------------------------------------------------------------------------------- /回溯法/77.combinations.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=77 lang=cpp 3 | * 4 | * [77] Combinations 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector> combine(int n, int k) { 11 | if (k <= 0 || n <= 0) return res; 12 | vector track; 13 | comb(n, k, 1, track); 14 | return res; 15 | } 16 | 17 | void comb(int n, int k, int left, vector& sub) 18 | { 19 | if (sub.size() >= k) 20 | { 21 | res.push_back(sub); 22 | return; 23 | } 24 | for (int i = left; i < n+1; i++) 25 | { 26 | sub.push_back(i); 27 | comb(n, k, i + 1, sub); 28 | sub.pop_back(); 29 | } 30 | } 31 | private: 32 | vector> res; 33 | }; 34 | // @lc code=end 35 | 36 | -------------------------------------------------------------------------------- /回溯法/78.subsets.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=78 lang=cpp 3 | * 4 | * [78] Subsets 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector> subsets(vector& nums) { 11 | vector a; 12 | backtrack(nums, 0, a); 13 | return res; 14 | } 15 | 16 | 17 | void backtrack(const vector& nums, int start, vector& subset) 18 | { 19 | res.push_back(subset); // push_back 的时候调用拷贝构造函数 存的是副本 20 | for (size_t i = start; i < nums.size(); i++) 21 | { 22 | subset.push_back(nums[i]); 23 | backtrack(nums, i + 1, subset); 24 | subset.pop_back(); 25 | } 26 | } 27 | private: 28 | vector> res; 29 | }; 30 | // @lc code=end 31 | 32 | -------------------------------------------------------------------------------- /回溯法/921.minimum-add-to-make-parentheses-valid.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=921 lang=cpp 3 | * 4 | * [921] Minimum Add to Make Parentheses Valid 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int minAddToMakeValid(string s) { 11 | int right = 0; 12 | int count = 0; 13 | for (int i = 0; i < s.size(); i++) 14 | { 15 | if (s[i] == '(') 16 | { 17 | right += 1; // 右括号需要一个 18 | } 19 | else 20 | { 21 | right -= 1; 22 | if (right == -1) 23 | { 24 | count++; // 需要插入左括号 25 | right = 0; 26 | } 27 | } 28 | } 29 | return count + right; 30 | } 31 | }; 32 | // @lc code=end 33 | 34 | -------------------------------------------------------------------------------- /图论/1254.number-of-closed-islands.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1254 lang=cpp 3 | * 4 | * [1254] Number of Closed Islands 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int closedIsland(vector>& grid) { 11 | 12 | } 13 | }; 14 | // @lc code=end 15 | 16 | -------------------------------------------------------------------------------- /图论/200.number-of-islands.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=200 lang=cpp 3 | * 4 | * [200] Number of Islands 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int numIslands(vector>& grid) { 11 | int m = grid.size(); 12 | int n = grid[0].size(); 13 | int res = 0; 14 | for (int i = 0; i < m; i++) 15 | { 16 | for (int j = 0; j < n; j++) 17 | { 18 | if (grid[i][j] == '1') 19 | { 20 | res++; 21 | floodFill(grid, i, j); 22 | } 23 | } 24 | } 25 | return res; 26 | } 27 | 28 | void floodFill(vector>& grid, int i, int j) { 29 | int m = grid.size(); 30 | int n = grid[0].size(); 31 | if (i < 0 || j < 0 || i >= m || j >= n) 32 | return; 33 | if (grid[i][j] == '0') 34 | return; 35 | 36 | grid[i][j] = '0'; 37 | floodFill(grid, i-1, j); 38 | floodFill(grid, i, j-1); 39 | floodFill(grid, i+1, j); 40 | floodFill(grid, i, j+1); 41 | } 42 | }; 43 | // @lc code=end 44 | 45 | -------------------------------------------------------------------------------- /图论/797.all-paths-from-source-to-target.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=797 lang=cpp 3 | * 4 | * [797] All Paths From Source to Target 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector> allPathsSourceTarget(vector>& graph) { 11 | vector> res; 12 | vector path; 13 | goPath(graph, 0, res, path); 14 | return res; 15 | } 16 | 17 | void goPath(const vector>& graph, int index, vector>& res, vector& path) 18 | { 19 | if (index >= graph.size()) return; 20 | path.push_back(index); 21 | if (index == (graph.size() - 1)) 22 | { 23 | res.push_back(path); 24 | path.pop_back(); // 除此之外可能还有别的路径 25 | return; 26 | } 27 | for (int i = 0; i < graph[index].size(); i++) 28 | { 29 | goPath(graph, graph[index][i], res, path); 30 | } 31 | path.pop_back(); 32 | } 33 | 34 | 35 | }; 36 | // @lc code=end 37 | 38 | -------------------------------------------------------------------------------- /字符串/.vscode/c_cpp_properties.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "name": "windows-gcc-x64", 5 | "includePath": [ 6 | "${workspaceFolder}/**" 7 | ], 8 | "compilerPath": "gcc", 9 | "cStandard": "${default}", 10 | "cppStandard": "${default}", 11 | "intelliSenseMode": "windows-gcc-x64", 12 | "compilerArgs": [ 13 | "" 14 | ] 15 | } 16 | ], 17 | "version": 4 18 | } -------------------------------------------------------------------------------- /字符串/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "C/C++ Runner: Debug Session", 6 | "type": "cppdbg", 7 | "request": "launch", 8 | "args": [], 9 | "stopAtEntry": false, 10 | "externalConsole": false, 11 | "cwd": "c:/Users/fengjie/Nutstore/1/leetcode/字符串", 12 | "program": "c:/Users/fengjie/Nutstore/1/leetcode/字符串/build/Debug/outDebug", 13 | "MIMode": "gdb", 14 | "miDebuggerPath": "gdb", 15 | "setupCommands": [ 16 | { 17 | "description": "Enable pretty-printing for gdb", 18 | "text": "-enable-pretty-printing", 19 | "ignoreFailures": true 20 | } 21 | ] 22 | } 23 | ] 24 | } -------------------------------------------------------------------------------- /字符串/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "C_Cpp_Runner.cCompilerPath": "gcc", 3 | "C_Cpp_Runner.cppCompilerPath": "g++", 4 | "C_Cpp_Runner.debuggerPath": "gdb", 5 | "C_Cpp_Runner.cStandard": "", 6 | "C_Cpp_Runner.cppStandard": "", 7 | "C_Cpp_Runner.msvcBatchPath": "", 8 | "C_Cpp_Runner.useMsvc": false, 9 | "C_Cpp_Runner.warnings": [ 10 | "-Wall", 11 | "-Wextra", 12 | "-Wpedantic" 13 | ], 14 | "C_Cpp_Runner.enableWarnings": true, 15 | "C_Cpp_Runner.warningsAsError": false, 16 | "C_Cpp_Runner.compilerArgs": [], 17 | "C_Cpp_Runner.linkerArgs": [], 18 | "C_Cpp_Runner.includePaths": [], 19 | "C_Cpp_Runner.includeSearch": [ 20 | "*", 21 | "**/*" 22 | ], 23 | "C_Cpp_Runner.excludeSearch": [ 24 | "**/build", 25 | "**/build/**", 26 | "**/.*", 27 | "**/.*/**", 28 | "**/.vscode", 29 | "**/.vscode/**" 30 | ] 31 | } -------------------------------------------------------------------------------- /字符串/58.length-of-last-word.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=58 lang=cpp 3 | * 4 | * [58] Length of Last Word 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int lengthOfLastWord(string s) { 11 | int i = s.length() - 1; 12 | while (i >= 0 && s[i] == ' ') // 从末尾找第一个非空格 13 | i--; 14 | if (i < 0) return s.length(); 15 | int n1 = i; 16 | while (i >= 0 && s[i] != ' ') // 找到单词前一个空格 17 | i--; 18 | int n2 = i; 19 | return n1 - n2; 20 | } 21 | }; 22 | // @lc code=end 23 | 24 | -------------------------------------------------------------------------------- /字符串/6.zigzag-conversion.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=6 lang=cpp 3 | * 4 | * [6] Zigzag Conversion 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | string convert(string s, int numRows) { 11 | if (numRows == 1) 12 | return s; 13 | 14 | vector zig(numRows, ""); 15 | int r = 0; 16 | bool down = true; 17 | for (int i = 0; i < s.length(); i++) { 18 | zig[r] += s[i]; 19 | if (r == 0) { 20 | down = true; 21 | } 22 | else if (r == numRows - 1) { 23 | down = false; 24 | } 25 | r = down ? r + 1 : r - 1; 26 | } 27 | string res = ""; 28 | for (int i = 0; i < zig.size(); i++) { 29 | res += zig[i]; 30 | } 31 | return res; 32 | } 33 | }; 34 | // @lc code=end 35 | 36 | -------------------------------------------------------------------------------- /字符串/67.add-binary.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=67 lang=cpp 3 | * 4 | * [67] Add Binary 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | string addBinary(string a, string b) { 11 | int an = a.length(); 12 | int bn = b.length(); 13 | int n = an > bn ? an : bn; 14 | string res = ""; 15 | int carry = 0; 16 | for (int i = 0; i < n; i++) { 17 | int v1 = i >= an ? 0 : stoi(a[an - 1 - i]); 18 | int v2 = i >= bn ? 0 : stoi(b[bn - 1 - i]); 19 | int r = v1 + v2 + carry; 20 | res = char(r % 2 + '0') + res; // r 为0 2 =>'0' 1 3 => '1' 21 | carry = (r >= 2 ? 1 : 0); 22 | } 23 | if (carry == 1) 24 | res = '1' + res; 25 | return res; 26 | } 27 | 28 | int stoi(char s) { 29 | return s - '0'; 30 | } 31 | }; 32 | // @lc code=end 33 | 34 | -------------------------------------------------------------------------------- /字符串/97.交错字符串.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=97 lang=cpp 3 | * 4 | * [97] 交错字符串 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | bool isInterleave(string s1, string s2, string s3) { 11 | 12 | } 13 | }; 14 | // @lc code=end 15 | 16 | -------------------------------------------------------------------------------- /已整理/141.linked-list-cycle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=141 lang=cpp 3 | * 4 | * [141] Linked List Cycle 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for singly-linked list. 10 | * struct ListNode { 11 | * int val; 12 | * ListNode *next; 13 | * ListNode(int x) : val(x), next(NULL) {} 14 | * }; 15 | */ 16 | class Solution { 17 | public: 18 | bool hasCycle(ListNode *head) { 19 | if (head == nullptr) 20 | return false; 21 | ListNode *p1, *p2; 22 | p1 = p2 = head; 23 | while (p2->next != nullptr && p2->next->next != nullptr) 24 | { 25 | p2 = p2->next->next; 26 | p1 = p1->next; 27 | if (p2 == p1) 28 | return true; 29 | } 30 | return false; 31 | } 32 | }; 33 | // @lc code=end 34 | 35 | -------------------------------------------------------------------------------- /已整理/142.linked-list-cycle-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=142 lang=cpp 3 | * 4 | * [142] Linked List Cycle II 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for singly-linked list. 10 | * struct ListNode { 11 | * int val; 12 | * ListNode *next; 13 | * ListNode(int x) : val(x), next(NULL) {} 14 | * }; 15 | */ 16 | class Solution { 17 | public: 18 | ListNode *detectCycle(ListNode *head) { 19 | if (head == nullptr) 20 | return nullptr; 21 | ListNode *fast, *slow; 22 | fast = slow = head; 23 | while (fast->next != nullptr && fast->next->next != nullptr) 24 | { 25 | fast = fast->next->next; 26 | slow = slow->next; 27 | // 有环 28 | if (fast == slow) 29 | { 30 | // slow 从head从新走,相遇即为环起点 31 | slow = head; 32 | while (fast != slow) 33 | { 34 | fast = fast->next; 35 | slow = slow->next; 36 | } 37 | return fast; 38 | } 39 | } 40 | return nullptr; 41 | } 42 | }; 43 | // @lc code=end 44 | 45 | -------------------------------------------------------------------------------- /已整理/3.longest-substring-without-repeating-characters.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=3 lang=cpp 3 | * 4 | * [3] Longest Substring Without Repeating Characters 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int lengthOfLongestSubstring(string s) { 11 | if (s.length() <= 0) 12 | return 0; 13 | 14 | unordered_map map; 15 | int start = 0; 16 | int maxlen = 0; 17 | for (int i = 0; i < s.length(); i++) 18 | { 19 | if (map.find(s[i]) == map.end()) // 未有重复 20 | map.insert({ s[i], i }); 21 | else 22 | { 23 | start = map[s[i]] + 1 > start ? map[s[i]] + 1 : start; 24 | map[s[i]] = i; 25 | } 26 | maxlen = max(maxlen, i - start + 1); 27 | } 28 | return maxlen; 29 | } 30 | 31 | }; 32 | // @lc code=end 33 | 34 | -------------------------------------------------------------------------------- /已整理/5.longest-palindromic-substring.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=5 lang=cpp 3 | * 4 | * [5] Longest Palindromic Substring 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | string longestPalindrome(string s) { 11 | string maxstr = ""; 12 | for (size_t i = 0; i < s.length(); i++) 13 | { 14 | string a = palindrome(s, i, i); 15 | string b = palindrome(s, i, i+1); 16 | maxstr = maxstr.length() > a.length() ? maxstr : a; 17 | maxstr = maxstr.length() > b.length() ? maxstr : b; 18 | } 19 | return maxstr; 20 | 21 | } 22 | 23 | string palindrome(string& s, int i, int j) { 24 | if (i > j) 25 | return ""; 26 | while (i >= 0 && j < s.length() && s[i] == s[j]) 27 | { 28 | --i; 29 | ++j; 30 | } 31 | return s.substr(i+1, j - i - 1); 32 | } 33 | }; 34 | // @lc code=end 35 | 36 | -------------------------------------------------------------------------------- /数学运算技巧/1201.丑数-iii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=1201 lang=cpp 3 | * 4 | * [1201] 丑数 III 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | // 单调函数,[1, ... , num] 中能被 a b c 整除的元素个数 11 | int f(int num, int a, int b, int c) 12 | { 13 | 14 | } 15 | 16 | int nthUglyNumber(int n, int a, int b, int c) { 17 | 18 | } 19 | 20 | int nthUglyNumber2(int n, int a, int b, int c) { 21 | vector ugly(n); 22 | long product_a = a, product_b = b, product_c = c; 23 | for (size_t i = 0; i < n; i++) 24 | { 25 | ugly[i] = min(min(product_a, product_b), product_c); 26 | 27 | while (ugly[i] >= product_a) 28 | { 29 | product_a += a; 30 | } 31 | while (ugly[i] >= product_b) 32 | { 33 | product_b += b; 34 | } 35 | while (ugly[i] >= product_c) 36 | { 37 | product_c += c; 38 | } 39 | } 40 | return ugly[n-1]; 41 | } 42 | }; 43 | // @lc code=end 44 | 45 | -------------------------------------------------------------------------------- /数学运算技巧/136.single-number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=136 lang=cpp 3 | * 4 | * [136] Single Number 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int singleNumber(vector& nums) { 11 | int o = 0; 12 | for (int item : nums) 13 | { 14 | o = o ^ item; 15 | } 16 | return o; 17 | } 18 | }; 19 | // @lc code=end 20 | 21 | -------------------------------------------------------------------------------- /数学运算技巧/137.只出现一次的数字-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=137 lang=cpp 3 | * 4 | * [137] 只出现一次的数字 II 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int singleNumber(vector& nums) { 11 | vector bits(32); 12 | for (int a : nums) { 13 | for (int i = 0; i < 32; i++) { 14 | if (a & (1 << i)) 15 | bits[i]++; 16 | } 17 | } 18 | int ans = 0; 19 | for (int i = 0; i < 32; i++) { 20 | if (bits[i] % 3 != 0) 21 | ans |= (1 << i); 22 | } 23 | return ans; 24 | } 25 | }; 26 | // @lc code=end 27 | 28 | -------------------------------------------------------------------------------- /数学运算技巧/168.excel-表列名称.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=168 lang=cpp 3 | * 4 | * [168] Excel 表列名称 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | string convertToTitle(int columnNumber) { 11 | string ans = ""; 12 | while (columnNumber) { 13 | columnNumber--; 14 | ans = string(1, 'A' + columnNumber % 26) + ans; 15 | columnNumber = columnNumber / 26; 16 | } 17 | return ans; 18 | } 19 | }; 20 | // @lc code=end 21 | 22 | -------------------------------------------------------------------------------- /数学运算技巧/171.excel-表列序号.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=171 lang=cpp 3 | * 4 | * [171] Excel 表列序号 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int titleToNumber(string columnTitle) { 11 | int ans = 0; 12 | for (int i = 0; i < columnTitle.size(); i++) { 13 | char c = columnTitle[i]; 14 | ans += pow(26, columnTitle.size() - i - 1) * (c - 'A' + 1); 15 | } 16 | return ans; 17 | } 18 | }; 19 | // @lc code=end 20 | 21 | -------------------------------------------------------------------------------- /数学运算技巧/172.factorial-trailing-zeroes.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SherlockUnknowEn/leetcode/efbecf23578d1a179b3d10a984f87c25e1c780bd/数学运算技巧/172.factorial-trailing-zeroes.cpp -------------------------------------------------------------------------------- /数学运算技巧/191.number-of-1-bits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=191 lang=cpp 3 | * 4 | * [191] Number of 1 Bits 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int hammingWeight(uint32_t n) { 11 | int sum = 0; 12 | while (n != 0) 13 | { 14 | sum++; 15 | n = n&(n-1); 16 | } 17 | return sum; 18 | } 19 | 20 | // int hammingWeight(uint32_t n) { 21 | // int sum = 0; 22 | // uint32_t i = 1; 23 | // while (n != 0) 24 | // { 25 | // if (n & i == 1) 26 | // { 27 | // sum++; 28 | // } 29 | // n = n >> 1; 30 | // } 31 | // return sum; 32 | // } 33 | }; 34 | // @lc code=end 35 | 36 | -------------------------------------------------------------------------------- /数学运算技巧/231.power-of-two.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=231 lang=cpp 3 | * 4 | * [231] Power of Two 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | bool isPowerOfTwo(int n) { 11 | if (n <= 0) 12 | return false; 13 | return (n & (n-1)) == 0; 14 | } 15 | }; 16 | // @lc code=end 17 | 18 | -------------------------------------------------------------------------------- /数学运算技巧/263.丑数.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=263 lang=cpp 3 | * 4 | * [263] 丑数 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | bool isUgly(int n) { 11 | if (n == 0) 12 | return false; 13 | while (n % 2 == 0) 14 | n = n / 2; 15 | while (n % 3 == 0) 16 | n = n / 3; 17 | while (n % 5 == 0) 18 | n = n / 5; 19 | return n == 1; 20 | } 21 | }; 22 | // @lc code=end 23 | 24 | -------------------------------------------------------------------------------- /数学运算技巧/264.丑数-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=264 lang=cpp 3 | * 4 | * [264] 丑数 II 5 | */ 6 | 7 | // 1*2 -> 2*2 -> 3*2 -> 4*2 -> 5*2 -> 6*2 -> 8*2 能被2整除的丑数 8 | // 1*3 -> 2*3 -> 3*3 -> 4*3 -> 5*3 -> 6*3 -> 8*3 能被3整除的丑数 9 | // 1*5 -> 2*5 -> 3*5 -> 4*5 -> 5*5 -> 6*5 -> 8*5 能被5整除的丑数 10 | // 合并链表 11 | 12 | 13 | // @lc code=start 14 | class Solution { 15 | public: 16 | int nthUglyNumber(int n) { 17 | int product2 = 1, product3 = 1, product5 = 1; 18 | int p2 = 0, p3 = 0, p5 = 0; 19 | vector ugly(n, 0); 20 | for (int i = 0; i < n; i++) 21 | { 22 | ugly[i] = min(min(product2, product3), product5); 23 | if (ugly[i] >= product2) 24 | { 25 | product2 = ugly[p2] * 2; 26 | p2++; 27 | } 28 | if (ugly[i] >= product3) 29 | { 30 | product3 = ugly[p3] * 3; 31 | p3++; 32 | } 33 | if (ugly[i] >= product5) 34 | { 35 | product5 = ugly[p5] * 5; 36 | p5++; 37 | } 38 | } 39 | return ugly[n-1]; 40 | } 41 | }; 42 | // @lc code=end 43 | -------------------------------------------------------------------------------- /数学运算技巧/313.超级丑数.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=313 lang=cpp 3 | * 4 | * [313] 超级丑数 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | 11 | 12 | int nthSuperUglyNumber(int n, vector& primes) { 13 | vector ugly(n); 14 | vector product(primes.size(), 1); 15 | vector p(primes.size(), 0); 16 | for (size_t i = 0; i < n; i++) 17 | { 18 | ugly[i] = *min_element(product.begin(), product.end()); 19 | for (size_t j = 0; j < primes.size(); j++) 20 | { 21 | int point = p[j]; 22 | if (ugly[i] >= product[j]) 23 | { 24 | product[j] = ugly[point] * primes[j]; 25 | p[j] = p[j] + 1; 26 | } 27 | } 28 | } 29 | 30 | return ugly[n-1]; 31 | } 32 | }; 33 | // @lc code=end 34 | 35 | -------------------------------------------------------------------------------- /数学运算技巧/50.pow-x-n.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=50 lang=cpp 3 | * 4 | * [50] Pow(x, n) 5 | */ 6 | 7 | x^n = x^2 ^ n/2 8 | 9 | // @lc code=start 10 | class Solution { 11 | public: 12 | double myPow(double x, int n) { 13 | if (x == 0 || x == 1 || n == 1) // 0 和 1 不需要计算 14 | return x; 15 | if (n == 0) 16 | return 1; 17 | if (n == INT_MIN) // 防止 int 最小值-2147483648转成正数后溢出 18 | return myPow(x, n + 1) / x; 19 | if (n < 0) 20 | return 1 / myPow(x, -n); 21 | if (n % 2 == 0) 22 | return myPow(x * x, n / 2); 23 | else 24 | return x * myPow(x, n - 1); 25 | } 26 | }; 27 | // @lc code=end 28 | 29 | -------------------------------------------------------------------------------- /数学运算技巧/89.格雷编码.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=89 lang=cpp 3 | * 4 | * [89] 格雷编码 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector grayCode(int n) { 11 | // [0, 65535] 12 | unordered_set set; 13 | int nums = pow(2, n); 14 | vector code(nums); 15 | code[0] = 0; 16 | set.insert(0); 17 | for (int i = 1; i < nums; i++) { 18 | for (int j = 0; j < n; j++) { 19 | int c = code[i - 1] ^ (1 << j); 20 | // printf("(1 << j) = %d, c = %d \n", (1 << j), c); 21 | if (set.find(c) == set.end()) { 22 | code[i] = c; 23 | set.insert(c); 24 | break; 25 | } 26 | } 27 | } 28 | return code; 29 | } 30 | }; 31 | // @lc code=end 32 | 33 | -------------------------------------------------------------------------------- /数组/1.two-sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1 lang=cpp 3 | * 4 | * [1] Two Sum 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector twoSum(vector& nums, int target) { 11 | unordered_map map; 12 | for (int i = 0; i < nums.size(); i++) 13 | { 14 | map[nums[i]] = i; 15 | } 16 | for (int i = 0; i < nums.size(); i++) 17 | { 18 | int val = target - nums[i]; 19 | if (map.find(val) != map.end() && map[val] != i) 20 | { 21 | return { i, map[val] }; 22 | } 23 | } 24 | return { -1, -1 }; 25 | } 26 | }; 27 | // @lc code=end 28 | 29 | -------------------------------------------------------------------------------- /数组/1094.car-pooling.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1094 lang=cpp 3 | * 4 | * [1094] Car Pooling 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | bool carPooling(vector>& trips, int capacity) { 11 | const int MaxLen = 1001; 12 | vector diff(MaxLen); 13 | for (int i = 0; i < trips.size(); i++) 14 | { 15 | int numsPass = trips[i][0]; 16 | int from = trips[i][1]; 17 | int to = trips[i][2]; 18 | if (numsPass > capacity) 19 | { 20 | return false; // base case 0站上车人数已经大于capcity 21 | } 22 | 23 | diff[from] += numsPass; 24 | if (to < MaxLen - 1) // to 站已经下车 应该在此站减去 而不是 to+1 站减去 25 | { 26 | diff[to] -= numsPass; 27 | } 28 | } 29 | 30 | for (int i = 1; i < MaxLen; i++) 31 | { 32 | diff[i] = diff[i] + diff[i-1]; 33 | if (diff[i] > capacity) 34 | { 35 | return false; 36 | } 37 | 38 | } 39 | return true; 40 | } 41 | }; 42 | // @lc code=end 43 | 44 | -------------------------------------------------------------------------------- /数组/1109.corporate-flight-bookings.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1109 lang=cpp 3 | * 4 | * [1109] Corporate Flight Bookings 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector corpFlightBookings(vector>& bookings, int n) { 11 | vector total(n); 12 | for (int i = 0; i < bookings.size(); i++) 13 | { 14 | int first = bookings[i][0]; 15 | int last = bookings[i][1]; 16 | int seats = bookings[i][2]; 17 | total[first - 1] += seats; 18 | if (last < total.size()) 19 | { 20 | total[last] -= seats; 21 | } 22 | } 23 | // 还原total 24 | for (int i = 1; i < total.size(); i++) 25 | { 26 | total[i] = total[i] + total[i-1]; 27 | } 28 | return total; 29 | } 30 | }; 31 | // @lc code=end 32 | 33 | -------------------------------------------------------------------------------- /数组/118.pascals-triangle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=118 lang=cpp 3 | * 4 | * [118] Pascal's Triangle 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector> generate(int numRows) { 11 | if (numRows == 1) 12 | { 13 | vector> a = {{1}}; 14 | return a; 15 | } 16 | 17 | vector> res = {{1}, {1, 1}}; 18 | for (int i = 2; i < numRows; i++) 19 | { 20 | vector a; 21 | a.push_back(1); 22 | for (int j = 0; j < res[i-1].size() - 1; j++) 23 | { 24 | int m = res[i-1][j] + res[i-1][j+1]; 25 | a.push_back(m); 26 | } 27 | a.push_back(1); 28 | res.push_back(a); 29 | } 30 | return res; 31 | } 32 | }; 33 | // @lc code=end 34 | 35 | 36 | -------------------------------------------------------------------------------- /数组/119.pascals-triangle-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=119 lang=cpp 3 | * 4 | * [119] Pascal's Triangle II 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector getRow(int rowIndex) { 11 | if (rowIndex == 0) 12 | { 13 | return { 1 }; 14 | } 15 | vector cur = {1, 1}; 16 | for (int i = 1; i < rowIndex; i++) 17 | { 18 | vector next; 19 | next.push_back(1); 20 | for (int j = 0; j < cur.size() - 1; j++) 21 | { 22 | next.push_back(cur[j] + cur[j+1]); 23 | } 24 | next.push_back(1); 25 | cur = next; 26 | } 27 | 28 | return cur; 29 | } 30 | }; 31 | // @lc code=end 32 | 33 | -------------------------------------------------------------------------------- /数组/120.triangle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=120 lang=cpp 3 | * 4 | * [120] Triangle 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int minimumTotal(vector>& triangle) { 11 | int n = triangle.size(); 12 | if (n == 1) 13 | return triangle[0][0]; 14 | 15 | vector> dp(n, vector(n)); 16 | dp[0][0] = triangle[0][0]; 17 | 18 | for (int i = 1; i < n; i++) 19 | { 20 | for (int j = 0; j <= i; j++) 21 | { 22 | if (j == 0) 23 | dp[i][j] = dp[i-1][j] + triangle[i][j]; 24 | else if (j == i) 25 | dp[i][j] = dp[i-1][j-1] + triangle[i][j]; 26 | else 27 | dp[i][j] = min(dp[i-1][j-1], dp[i-1][j]) + triangle[i][j]; 28 | } 29 | } 30 | 31 | int total = INT_MAX; 32 | for (int j = 0; j < n; j++) { 33 | total = dp[n-1][j] < total ? dp[n-1][j] : total; 34 | } 35 | return total; 36 | } 37 | 38 | }; 39 | // @lc code=end 40 | 41 | -------------------------------------------------------------------------------- /数组/128.最长连续序列.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=128 lang=cpp 3 | * 4 | * [128] 最长连续序列 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int longestConsecutive(vector& nums) { 11 | unordered_set set; 12 | set.insert(nums.begin(), nums.end()); 13 | int max = 0; 14 | for (int x : set) { 15 | // 最左侧才开始查找 16 | if (set.find(x - 1) == set.end()) { 17 | int y = x + 1; 18 | while (set.find(y) != set.end()) { 19 | y++; 20 | } 21 | max = max < (y - x) ? y - x : max; 22 | } 23 | } 24 | return max; 25 | } 26 | }; 27 | // @lc code=end 28 | 29 | -------------------------------------------------------------------------------- /数组/152.乘积最大子数组.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=152 lang=cpp 3 | * 4 | * [152] 乘积最大子数组 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int maxProduct(vector& nums) { 11 | int n = nums.size(); 12 | int max = INT_MIN; 13 | int product = 1; 14 | // 区间一定出现在最左或者最右 15 | // 两边有 1. 两正或者两负, 可以扩大区间 16 | // 2. 一正一负, 也能扩大一边的区间 17 | for (int i = 0; i < n; i++) { 18 | product *= nums[i]; 19 | max = product > max ? product : max; 20 | if (product == 0) 21 | product = 1; 22 | } 23 | product = 1; 24 | for (int i = n - 1; i >= 0; i--) { 25 | product *= nums[i]; 26 | max = product > max ? product : max; 27 | if (product == 0) 28 | product = 1; 29 | } 30 | return max; 31 | } 32 | }; 33 | // @lc code=end 34 | 35 | -------------------------------------------------------------------------------- /数组/228.汇总区间.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=228 lang=cpp 3 | * 4 | * [228] 汇总区间 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector summaryRanges(vector& nums) { 11 | vector ans; 12 | int i = 0; 13 | int n = nums.size(); 14 | // 分组循环 15 | while (i < n) { 16 | int start = i; 17 | while (i < n-1 && nums[i] + 1 == nums[i + 1]) 18 | i++; 19 | if (nums[i] == nums[start]) { 20 | ans.push_back(to_string(nums[i])); 21 | } else { 22 | ans.push_back(to_string(nums[start]) + string("->") + to_string(nums[i])); 23 | } 24 | i++; 25 | } 26 | return ans; 27 | } 28 | }; 29 | // @lc code=end 30 | 31 | -------------------------------------------------------------------------------- /数组/27.remove-element.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=27 lang=cpp 3 | * 4 | * [27] Remove Element 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int removeElement(vector& nums, int val) { 11 | int cur = 0; 12 | int i = 0; 13 | int length = 0; 14 | while (i < nums.size()) 15 | { 16 | if (nums[i] != val) 17 | { 18 | nums[cur] = nums[i]; 19 | i++; 20 | cur++; 21 | length++; 22 | } 23 | else 24 | { 25 | i++; 26 | } 27 | } 28 | return length; 29 | } 30 | }; 31 | // @lc code=end 32 | 33 | -------------------------------------------------------------------------------- /数组/303.range-sum-query-immutable.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=303 lang=cpp 3 | * 4 | * [303] Range Sum Query - Immutable 5 | */ 6 | 7 | // @lc code=start 8 | class NumArray { 9 | public: 10 | NumArray(vector& nums) { 11 | data.clear(); 12 | data.insert(data.begin(), nums.size() + 1, 0); 13 | for (int i = 0; i < nums.size(); i++) 14 | { 15 | data[i+1] = data[i] + nums[i]; 16 | } 17 | } 18 | 19 | int sumRange(int left, int right) { 20 | return data[right + 1] - data[left]; 21 | } 22 | private: 23 | vector data; 24 | }; 25 | 26 | /** 27 | * Your NumArray object will be instantiated and called as such: 28 | * NumArray* obj = new NumArray(nums); 29 | * int param_1 = obj->sumRange(left,right); 30 | */ 31 | // @lc code=end 32 | 33 | -------------------------------------------------------------------------------- /数组/32.longest-valid-parentheses.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=32 lang=cpp 3 | * 4 | * [32] Longest Valid Parentheses 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int longestValidParentheses(string s) { 11 | int n = s.length(); 12 | vector dp(n); 13 | int maxval = 0; 14 | for (int i = 1; i < n; i++) 15 | { 16 | if (s[i] == ')') 17 | { 18 | int j = i - 1 - dp[i-1]; 19 | if (j >= 0 && s[j] == '(') 20 | { 21 | dp[i] = dp[i-1] + 2 + ( j-1>=0 ? dp[j-1] : 0 ); 22 | } 23 | } 24 | } 25 | for (int i = 0; i < dp.size(); i++) 26 | { 27 | maxval = max(maxval, dp[i]); 28 | } 29 | return maxval; 30 | } 31 | }; 32 | // @lc code=end 33 | 34 | -------------------------------------------------------------------------------- /数组/48.rotate-image.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=48 lang=cpp 3 | * 4 | * [48] Rotate Image 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | void rotate(vector>& matrix) { 11 | const int n = matrix.size(); 12 | for (size_t i = 0; i < (n + 1) / 2; i++) // +1 为了避免奇数时,漏处理最中间的元素 13 | { 14 | for (size_t j = 0; j < n / 2; j++) 15 | { 16 | int temp = matrix[i][j]; 17 | matrix[i][j] = matrix[n - 1 - j][i]; 18 | matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j]; 19 | matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i]; 20 | matrix[j][n - 1 - i] = temp; 21 | } 22 | } 23 | } 24 | }; 25 | // @lc code=end 26 | 27 | -------------------------------------------------------------------------------- /数组/53.maximum-subarray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=53 lang=cpp 3 | * 4 | * [53] Maximum Subarray 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int maxSubArray(vector& nums) { 11 | if (nums.size() <= 0) 12 | return 0; 13 | if (nums.size() == 1) 14 | return nums[0]; 15 | 16 | int pre = 0; 17 | maxSub(nums, pre, 0); 18 | return sum; 19 | } 20 | 21 | int maxSub(const vector& nums, int pre, int cur) 22 | { 23 | if (cur > nums.size() - 1) 24 | return INT_MIN; 25 | int a = pre + nums[cur]; 26 | int b = maxSub(nums, 0, cur + 1); 27 | sum = max(a, sum); 28 | sum = max(b, sum); 29 | return a; 30 | } 31 | private: 32 | int sum = 0; 33 | }; 34 | // @lc code=end 35 | 36 | -------------------------------------------------------------------------------- /数组/704.binary-search.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=704 lang=cpp 3 | * 4 | * [704] Binary Search 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int search(vector& nums, int target) { 11 | 12 | int left = 0; 13 | int right = nums.size() - 1; 14 | while (left <= right) 15 | { 16 | int mid = left + (right - left) / 2; 17 | if (nums[mid] == target) 18 | return mid; 19 | else if (nums[mid] > target) 20 | right = mid - 1; 21 | else if (nums[mid] < target) 22 | left = mid + 1; 23 | } 24 | return -1; 25 | } 26 | }; 27 | // @lc code=end 28 | 29 | -------------------------------------------------------------------------------- /数组/85.maximal-rectangle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=85 lang=cpp 3 | * 4 | * [85] Maximal Rectangle 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int maximalRectangle(vector>& matrix) { 11 | 12 | } 13 | }; 14 | // @lc code=end 15 | 16 | -------------------------------------------------------------------------------- /数组/85.最大矩形.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=85 lang=cpp 3 | * 4 | * [85] 最大矩形 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int maximalRectangle(vector>& matrix) { 11 | 12 | } 13 | }; 14 | // @lc code=end 15 | 16 | -------------------------------------------------------------------------------- /数组/887.super-egg-drop.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=887 lang=cpp 3 | * 4 | * [887] Super Egg Drop 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int superEggDrop(int k, int n) { 11 | 12 | } 13 | }; 14 | // @lc code=end 15 | 16 | -------------------------------------------------------------------------------- /栈/1078.bigram-分词.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=1078 lang=cpp 3 | * 4 | * [1078] Bigram 分词 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector findOcurrences(string text, string first, string second) { 11 | vector words = split(text, ' '); 12 | vector ans; 13 | 14 | for (int i = 0; i < words.size() - 2; i++) { 15 | if (words[i] == first && words[i+1] == second) { 16 | ans.push_back(words[i+2]); 17 | } 18 | } 19 | return ans; 20 | } 21 | 22 | vector split(const string& text, char sp) { 23 | vector ans; 24 | string a = ""; 25 | for (char c : text) { 26 | if (c == sp) { 27 | if (a != "") 28 | ans.push_back(a); 29 | a = ""; 30 | continue; 31 | } else { 32 | a = a + c; 33 | } 34 | } 35 | if (a != "") 36 | ans.push_back(a); 37 | return ans; 38 | } 39 | }; 40 | // @lc code=end 41 | 42 | -------------------------------------------------------------------------------- /栈/1128.等价多米诺骨牌对的数量.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=1128 lang=cpp 3 | * 4 | * [1128] 等价多米诺骨牌对的数量 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int numEquivDominoPairs(vector>& dominoes) { 11 | int sz = dominoes.size(); 12 | vector memo(100); 13 | int cnt = 0; 14 | for (int i = 0; i < sz; i++) { 15 | // vector& t = dominoes[i]; 16 | int a = max(dominoes[i][0], dominoes[i][1]); 17 | int b = min(dominoes[i][0], dominoes[i][1]); 18 | int c = a * 10 + b; 19 | cnt += memo[c]; 20 | memo[c]++; 21 | } 22 | return cnt; 23 | } 24 | }; 25 | // @lc code=end 26 | 27 | -------------------------------------------------------------------------------- /栈/150.逆波兰表达式求值.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=150 lang=cpp 3 | * 4 | * [150] 逆波兰表达式求值 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int evalRPN(vector& tokens) { 11 | stack nums; 12 | for (auto& t : tokens) { 13 | if (t == "+" || t == "-" || t == "*" || t == "/") { 14 | int a = nums.top(); 15 | nums.pop(); 16 | int b = nums.top(); 17 | nums.pop(); 18 | if (t == "+") { 19 | nums.push(b + a); 20 | } 21 | if (t == "-") { 22 | nums.push(b - a); 23 | } 24 | if (t == "*") { 25 | nums.push(b * a); 26 | } 27 | if (t == "/") { 28 | nums.push(b / a); 29 | } 30 | } else { 31 | nums.push(stoi(t)); 32 | } 33 | } 34 | // printf("nums.size() = %d\n", nums.size()); 35 | return nums.top(); 36 | } 37 | }; 38 | // @lc code=end 39 | 40 | -------------------------------------------------------------------------------- /栈/155.最小栈.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=155 lang=cpp 3 | * 4 | * [155] 最小栈 5 | */ 6 | 7 | // @lc code=start 8 | class MinStack { 9 | public: 10 | MinStack() { 11 | 12 | } 13 | 14 | void push(int val) { 15 | data.push(val); 16 | } 17 | 18 | void pop() { 19 | data.pop(); 20 | } 21 | 22 | int top() { 23 | int a = data.top(); 24 | data.pop(); 25 | return a; 26 | } 27 | 28 | int getMin() { 29 | 30 | } 31 | 32 | private: 33 | stack data; 34 | stack m; 35 | }; 36 | 37 | /** 38 | * Your MinStack object will be instantiated and called as such: 39 | * MinStack* obj = new MinStack(); 40 | * obj->push(val); 41 | * obj->pop(); 42 | * int param_3 = obj->top(); 43 | * int param_4 = obj->getMin(); 44 | */ 45 | // @lc code=end 46 | 47 | -------------------------------------------------------------------------------- /栈/225.用队列实现栈.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=225 lang=cpp 3 | * 4 | * [225] 用队列实现栈 5 | */ 6 | 7 | // @lc code=start 8 | class MyStack { 9 | public: 10 | MyStack() { 11 | q1 = &queue1; 12 | q2 = &queue2; 13 | } 14 | 15 | void push(int x) { 16 | q1->push(x); 17 | while (!q2->empty()) { 18 | q1->push(q2->front()); 19 | q2->pop(); 20 | } 21 | queue* tmp = q1; 22 | q1 = q2; 23 | q2 = tmp; 24 | } 25 | 26 | int pop() { 27 | int a = q2->front(); 28 | q2->pop(); 29 | return a; 30 | } 31 | 32 | int top() { 33 | return q2->front(); 34 | } 35 | 36 | bool empty() { 37 | return q1->empty() && q2->empty(); 38 | } 39 | 40 | private: 41 | queue queue1; // 1 2 3 4 5 42 | queue queue2; 43 | queue* q1; 44 | queue* q2; 45 | }; 46 | 47 | /** 48 | * Your MyStack object will be instantiated and called as such: 49 | * MyStack* obj = new MyStack(); 50 | * obj->push(x); 51 | * int param_2 = obj->pop(); 52 | * int param_3 = obj->top(); 53 | * bool param_4 = obj->empty(); 54 | */ 55 | // @lc code=end 56 | 57 | -------------------------------------------------------------------------------- /栈/456.132-模式.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=456 lang=cpp 3 | * 4 | * [456] 132 模式 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | bool find132pattern(vector& nums) { 11 | // 1 3 2 ==> i j k 12 | int n = nums.size(); 13 | if (n < 3) return false; 14 | stack st; 15 | st.push(nums[n-1]); 16 | int k = INT_MIN; 17 | // k 是单调栈弹出元素过程中的最大值 18 | // j 为栈顶元素 19 | // 在弹出的元素中 寻找 j 和 k 20 | // 单调递减栈,弹出元素一定比栈顶元素小,即保证 j > k 21 | for (int i = n-2; i >= 0; i--) { 22 | if (nums[i] < k) 23 | return true; 24 | 25 | while (!st.empty() && nums[i] > st.top()) { 26 | k = max(st.top(), k); 27 | st.pop(); 28 | } 29 | st.push(nums[i]); 30 | } 31 | // 3 1 4 1 2 32 | return false; 33 | } 34 | }; 35 | // @lc code=end 36 | 37 | -------------------------------------------------------------------------------- /栈/682.棒球比赛.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=682 lang=cpp 3 | * 4 | * [682] 棒球比赛 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int calPoints(vector& operations) { 11 | vector scores; 12 | for (string& s : operations) { 13 | if (s == "+") { 14 | int sz = scores.size(); 15 | scores.push_back(scores[sz - 1] + scores[sz - 2]); 16 | } else if (s == "D") { 17 | scores.push_back(scores[scores.size() - 1] * 2); 18 | } else if (s == "C") { 19 | scores.pop_back(); 20 | } else { 21 | scores.push_back(stoi(s)); 22 | } 23 | } 24 | int sum = 0; 25 | for (int c : scores) { 26 | sum += c; 27 | } 28 | return sum; 29 | } 30 | }; 31 | // @lc code=end 32 | 33 | -------------------------------------------------------------------------------- /栈/781.森林中的兔子.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=781 lang=cpp 3 | * 4 | * [781] 森林中的兔子 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int numRabbits(vector& answers) { 11 | vector mp(1001); 12 | int result = 0; 13 | for (int a : answers) { 14 | if (mp[a] > 0) { 15 | mp[a]--; 16 | } else { 17 | mp[a] = a; 18 | result += (a + 1); 19 | } 20 | } 21 | return result; 22 | } 23 | }; 24 | // @lc code=end 25 | 26 | -------------------------------------------------------------------------------- /栈/94.二叉树的中序遍历.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=94 lang=cpp 3 | * 4 | * [94] 二叉树的中序遍历 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | vector inorderTraversal(TreeNode* root) { 22 | vector ans; 23 | midorder(root, ans); 24 | return ans; 25 | } 26 | 27 | void midorder(TreeNode* root, vector& ans) { 28 | if (root == nullptr) return; 29 | midorder(root->left, ans); 30 | ans.push_back(root->val); 31 | midorder(root->right, ans); 32 | } 33 | }; 34 | // @lc code=end 35 | 36 | -------------------------------------------------------------------------------- /股票买卖问题/121.best-time-to-buy-and-sell-stock.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=121 lang=cpp 3 | * 4 | * [121] Best Time to Buy and Sell Stock 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int maxProfit(vector& prices) { 11 | int n = prices.size(); 12 | int min = prices[0]; 13 | int max = prices[0]; 14 | int sum = 0; 15 | // 滑动窗口/双指针 16 | for (int i = 0; i < n; i++) 17 | { 18 | if (prices[i] < min) 19 | { 20 | min = max = prices[i]; 21 | } 22 | if (prices[i] > max) 23 | { 24 | max = prices[i]; 25 | int p = max - min; 26 | sum = p > sum ? p : sum; 27 | } 28 | } 29 | return sum; 30 | } 31 | }; 32 | // @lc code=end 33 | 34 | -------------------------------------------------------------------------------- /股票买卖问题/122.best-time-to-buy-and-sell-stock-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=122 lang=cpp 3 | * 4 | * [122] Best Time to Buy and Sell Stock II 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int maxProfit(vector& prices) { 11 | int n = prices.size(); 12 | vector> dp(n, vector(2)); // dp[i][0] 第i天不持有股票的收益 dp[i][1]第i天持有股票的收益 13 | dp[0][1] = -prices[0]; 14 | for (int i = 1; i < n; i++) 15 | { 16 | dp[i][0] = max(dp[i-1][0], prices[i] + dp[i-1][1]); //不持有 1. 昨天也没持有且今天不买 2. 卖掉上一天的持有量 17 | dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i]); // 1. 继续持有上一天的 2. 昨天未持有,今天购入 18 | } 19 | return dp[n-1][0]; 20 | } 21 | }; 22 | // @lc code=end 23 | 24 | -------------------------------------------------------------------------------- /股票买卖问题/123.best-time-to-buy-and-sell-stock-iii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=123 lang=cpp 3 | * 4 | * [123] Best Time to Buy and Sell Stock III 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int maxProfit(vector& prices) { 11 | int n = prices.size(); 12 | vector>> dp(n, vector>(3, vector(2))); 13 | // base case 14 | dp[0][0][1] = INT_MIN; 15 | dp[0][1][1] = -prices[0]; // dp[i][k][0 or 1] 至第i天最多进行k次交易,手上持有或不持有股票 16 | dp[0][2][1] = -prices[0]; 17 | 18 | for (int i = 1; i < n; i++) 19 | { 20 | for (int j = 1; j < 3; j++) 21 | { 22 | /* code */ 23 | // 1. 昨天没持有,今天也没持有 24 | // 2. 昨天持有,今天卖出 25 | dp[i][j][0] = max(dp[i-1][j][0], dp[i-1][j][1] + prices[i]); 26 | // 1. 昨天持有,今天继续持有 27 | // 2. 昨天没持有,今天买入 28 | dp[i][j][1] = max(dp[i-1][j][1], dp[i-1][j-1][0] - prices[i]); 29 | } 30 | } 31 | return dp[n-1][2][0]; 32 | } 33 | }; 34 | // @lc code=end 35 | 36 | -------------------------------------------------------------------------------- /股票买卖问题/188.best-time-to-buy-and-sell-stock-iv.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=188 lang=cpp 3 | * 4 | * [188] Best Time to Buy and Sell Stock IV 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int maxProfit(int k, vector& prices) { 11 | //2\n[3,3,5,0,0,3,1,4]\n 6 12 | int n = prices.size(); 13 | if (k == 0 || n == 0) 14 | { 15 | return 0; 16 | } 17 | 18 | vector>> dp(n, vector>(k+1, vector(2))); 19 | for (int i = 0; i < n; i++) 20 | { 21 | dp[i][0][1] = INT_MIN; 22 | } 23 | for (int i = 1; i < k+1; i++) 24 | { 25 | dp[0][i][1] = -prices[0]; 26 | } 27 | 28 | for (int i = 1; i < n; i++) 29 | { 30 | for (int j = 1; j < k+1; j++) 31 | { 32 | dp[i][j][0] = max(dp[i-1][j][0], dp[i-1][j][1] + prices[i]); 33 | dp[i][j][1] = max(dp[i-1][j][1], dp[i-1][j-1][0] - prices[i]); 34 | } 35 | } 36 | return dp[n-1][k][0]; 37 | } 38 | }; 39 | // @lc code=end 40 | 41 | -------------------------------------------------------------------------------- /股票买卖问题/309.best-time-to-buy-and-sell-stock-with-cooldown.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=309 lang=cpp 3 | * 4 | * [309] Best Time to Buy and Sell Stock with Cooldown 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int maxProfit(vector& prices) { 11 | int n = prices.size(); 12 | if (n <= 1) 13 | return 0; 14 | vector> dp(n, vector(3)); // 0 未持有 1 持有 2 冷静期 15 | dp[0][1] = -prices[0]; 16 | for (int i = 1; i < n; i++) 17 | { 18 | dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i]); 19 | dp[i][1] = max(dp[i-1][1], dp[i-1][2] - prices[i]); 20 | dp[i][2] = dp[i-1][0]; // 冷静期是前一天未持有状态下的收益 21 | } 22 | return dp[n-1][0]; 23 | } 24 | }; 25 | // @lc code=end 26 | 27 | -------------------------------------------------------------------------------- /股票买卖问题/714.best-time-to-buy-and-sell-stock-with-transaction-fee.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=714 lang=cpp 3 | * 4 | * [714] Best Time to Buy and Sell Stock with Transaction Fee 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int maxProfit(vector& prices, int fee) { 11 | int n = prices.size(); 12 | if (n <= 1) 13 | return 0; 14 | vector> dp(n, vector(2)); 15 | dp[0][1] = -prices[0] - fee; 16 | for (int i = 1; i < n; i++) 17 | { 18 | dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i]); 19 | dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i] - fee); 20 | } 21 | return dp[n-1][0]; 22 | } 23 | }; 24 | // @lc code=end 25 | 26 | -------------------------------------------------------------------------------- /设计数据结构/155.最小栈.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=155 lang=cpp 3 | * 4 | * [155] 最小栈 5 | */ 6 | 7 | // @lc code=start 8 | class MinStack { 9 | public: 10 | MinStack() { 11 | 12 | } 13 | 14 | void push(int val) { 15 | if (minv.empty()) { 16 | minv.push(val); 17 | } else { 18 | minv.push(min(val, minv.top())); 19 | } 20 | data.push(val); 21 | } 22 | 23 | void pop() { 24 | data.pop(); 25 | minv.pop(); 26 | } 27 | 28 | int top() { 29 | return data.top(); 30 | } 31 | 32 | int getMin() { 33 | return minv.top(); 34 | } 35 | 36 | private: 37 | // 我们只需要设计一个数据结构,使得每个元素 a 与其相应的最小值 m 时刻保持一一对应 38 | stack data; 39 | stack minv; 40 | }; 41 | 42 | /** 43 | * Your MinStack object will be instantiated and called as such: 44 | * MinStack* obj = new MinStack(); 45 | * obj->push(val); 46 | * obj->pop(); 47 | * int param_3 = obj->top(); 48 | * int param_4 = obj->getMin(); 49 | */ 50 | // @lc code=end 51 | 52 | -------------------------------------------------------------------------------- /设计数据结构/234.palindrome-linked-list.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=234 lang=cpp 3 | * 4 | * [234] Palindrome Linked List 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for singly-linked list. 10 | * struct ListNode { 11 | * int val; 12 | * ListNode *next; 13 | * ListNode() : val(0), next(nullptr) {} 14 | * ListNode(int x) : val(x), next(nullptr) {} 15 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | bool isPalindrome(ListNode* head) { 21 | n = head; 22 | return valid(head); 23 | } 24 | 25 | bool valid(ListNode* head) 26 | { 27 | if (head == nullptr) 28 | return false; 29 | if (head->next != nullptr && !valid(head->next)) 30 | return false; 31 | bool res = n->val == head->val; 32 | n = n->next; 33 | return res; 34 | } 35 | 36 | private: 37 | ListNode* n; 38 | }; 39 | // @lc code=end 40 | 41 | -------------------------------------------------------------------------------- /设计数据结构/382.linked-list-random-node.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=382 lang=cpp 3 | * 4 | * [382] Linked List Random Node 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for singly-linked list. 10 | * struct ListNode { 11 | * int val; 12 | * ListNode *next; 13 | * ListNode() : val(0), next(nullptr) {} 14 | * ListNode(int x) : val(x), next(nullptr) {} 15 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | Solution(ListNode* head) { 21 | this->head = head; 22 | } 23 | 24 | int getRandom() { 25 | int c = -1; 26 | int i = 0; 27 | for (ListNode* p = head; p != nullptr; p=p->next) 28 | { 29 | i++; 30 | if (rand() % i == 0) 31 | c = p->val; 32 | } 33 | return c; 34 | } 35 | 36 | private: 37 | ListNode* head; 38 | }; 39 | 40 | /** 41 | * Your Solution object will be instantiated and called as such: 42 | * Solution* obj = new Solution(head); 43 | * int param_1 = obj->getRandom(); 44 | */ 45 | // @lc code=end 46 | 47 | -------------------------------------------------------------------------------- /设计数据结构/710.random-pick-with-blacklist.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=710 lang=cpp 3 | * 4 | * [710] Random Pick with Blacklist 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | Solution(int n, vector& blacklist) { 11 | 12 | } 13 | 14 | int pick() { 15 | 16 | } 17 | 18 | private: 19 | 20 | }; 21 | 22 | /** 23 | * Your Solution object will be instantiated and called as such: 24 | * Solution* obj = new Solution(n, blacklist); 25 | * int param_1 = obj->pick(); 26 | */ 27 | // @lc code=end 28 | 29 | -------------------------------------------------------------------------------- /贪心算法/1005.k-次取反后最大化的数组和.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=1005 lang=cpp 3 | * 4 | * [1005] K 次取反后最大化的数组和 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | static bool cmp(int a, int b) 11 | { 12 | return abs(a) > abs(b); 13 | } 14 | 15 | int largestSumAfterKNegations(vector& nums, int k) { 16 | int n = nums.size(); 17 | sort(nums.begin(), nums.end(), Solution::cmp); 18 | for (size_t i = 0; i < n; i++) 19 | { 20 | if (k <= 0) 21 | break; 22 | 23 | if (nums[i] < 0) 24 | { 25 | nums[i] = -nums[i]; 26 | k--; 27 | } 28 | } 29 | nums[n - 1] = (k % 2 == 0) ? nums[n - 1] : -nums[n - 1]; 30 | int sum = 0; 31 | for (int a : nums) 32 | { 33 | sum += a; 34 | } 35 | return sum; 36 | } 37 | }; 38 | // @lc code=end 39 | 40 | -------------------------------------------------------------------------------- /贪心算法/1288.remove-covered-intervals.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=1288 lang=cpp 3 | * 4 | * [1288] Remove Covered Intervals 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | static bool cmp(vector& v1, vector& v2) 11 | { 12 | if (v1[0] == v2[0]) 13 | { 14 | return v1[1] > v2[1]; 15 | } 16 | return v1[0] < v2[0]; 17 | } 18 | 19 | int removeCoveredIntervals(vector>& intervals) { 20 | sort(intervals.begin(), intervals.end(), cmp); 21 | int start = intervals[0][0]; 22 | int end = intervals[0][1]; 23 | int count = 0; 24 | for (int i = 1; i < intervals.size(); i++) 25 | { 26 | if (intervals[i][0] >= start && intervals[i][1] <= end) 27 | { 28 | count++; 29 | } 30 | else 31 | { 32 | start = intervals[i][0]; 33 | end = intervals[i][1]; 34 | } 35 | } 36 | return intervals.size() - count; 37 | } 38 | }; 39 | // @lc code=end 40 | 41 | -------------------------------------------------------------------------------- /贪心算法/134.gas-station.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=134 lang=cpp 3 | * 4 | * [134] Gas Station 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int canCompleteCircuit(vector& gas, vector& cost) { 11 | int n = gas.size(); 12 | int sum = 0; 13 | for (int i = 0; i < n; i++) 14 | { 15 | sum += (gas[i] - cost[i]); 16 | } 17 | if (sum < 0) 18 | { 19 | return -1; 20 | } 21 | int start = 0; 22 | int consume = 0; 23 | for (int i = 0; i < n; i++) 24 | { 25 | consume += (gas[i] - cost[i]); 26 | if (consume < 0) 27 | { 28 | start = i+1; 29 | consume = 0; 30 | } 31 | } 32 | return start == n ? 0 : start; 33 | } 34 | }; 35 | // @lc code=end 36 | 37 | -------------------------------------------------------------------------------- /贪心算法/135.分发糖果.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=135 lang=cpp 3 | * 4 | * [135] 分发糖果 5 | */ 6 | // @lc code=start 7 | class Solution { 8 | public: 9 | int candy(vector& ratings) { 10 | int n = ratings.size(); 11 | int count = 0; 12 | vector candy(n, 1); 13 | for (int i = 1; i < n; i++) 14 | { 15 | if (ratings[i] > ratings[i - 1]) 16 | { 17 | candy[i] = candy[i - 1] + 1; 18 | } 19 | } 20 | for (int i = n-2; i >= 0; i--) 21 | { 22 | if (ratings[i] > ratings[i + 1]) 23 | { 24 | candy[i] = max(candy[i], candy[i + 1] + 1); 25 | } 26 | } 27 | for (int i = 0; i < n; i++) 28 | { 29 | count += candy[i]; 30 | } 31 | 32 | return count; 33 | } 34 | }; 35 | // @lc code=end 36 | 37 | -------------------------------------------------------------------------------- /贪心算法/376.摆动序列.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=376 lang=cpp 3 | * 4 | * [376] 摆动序列 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int wiggleMaxLength(vector& nums) { 11 | if (nums.size() < 2) 12 | return nums.size(); 13 | int up = 1, down = 1; 14 | for (size_t i = 1; i < nums.size(); i++) { 15 | if (nums[i] - nums[i-1] > 0) 16 | up = down + 1; 17 | if (nums[i] - nums[i-1] < 0) 18 | down = up + 1; 19 | } 20 | return max(up, down); 21 | } 22 | }; 23 | // @lc code=end 24 | 25 | -------------------------------------------------------------------------------- /贪心算法/406.根据身高重建队列.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=406 lang=cpp 3 | * 4 | * [406] 根据身高重建队列 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | vector> reconstructQueue(vector>& people) { 11 | 12 | } 13 | }; 14 | // @lc code=end 15 | 16 | -------------------------------------------------------------------------------- /贪心算法/435.non-overlapping-intervals.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=435 lang=cpp 3 | * 4 | * [435] Non-overlapping Intervals 5 | */ 6 | 7 | // bool operator < (const vector& v1, const vector& v2) { 8 | // return v1[1] < v2[1]; 9 | // } 10 | 11 | 12 | 13 | // @lc code=start 14 | class Solution { 15 | public: 16 | static bool cmp(const vector& v1, const vector& v2) { 17 | return v1[1] < v2[1]; 18 | } 19 | int eraseOverlapIntervals(vector>& intervals) { 20 | sort(intervals.begin(), intervals.end(), cmp); 21 | int nums = 0; 22 | int end = INT_MIN; 23 | for (int i = 0; i < intervals.size(); i++) 24 | { 25 | if (intervals[i][0] >= end) 26 | { 27 | end = intervals[i][1]; 28 | nums++; 29 | } 30 | } 31 | return intervals.size() - nums; 32 | } 33 | }; 34 | 35 | // @lc code=end 36 | 37 | -------------------------------------------------------------------------------- /贪心算法/452.minimum-number-of-arrows-to-burst-balloons.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=452 lang=cpp 3 | * 4 | * [452] Minimum Number of Arrows to Burst Balloons 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | static bool cmp(const vector& v1, const vector& v2) { 11 | return v1[1] < v2[1]; 12 | } 13 | 14 | int findMinArrowShots(vector>& points) { 15 | sort(points.begin(), points.end(), cmp); 16 | int nums = 0; 17 | int end = INT_MIN; 18 | for (int i = 0; i < points.size(); i++) 19 | { 20 | if (points[i][0] > end) 21 | { 22 | end = points[i][1]; 23 | nums++; 24 | } 25 | } 26 | return max(nums, 1); // [[-2147483648,2147483647]] 时会返回0 27 | } 28 | }; 29 | // @lc code=end 30 | 31 | -------------------------------------------------------------------------------- /贪心算法/860.柠檬水找零.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=860 lang=cpp 3 | * 4 | * [860] 柠檬水找零 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | bool lemonadeChange(vector& bills) { 11 | int n = bills.size(); 12 | int five = 0; 13 | int ten = 0; 14 | for (size_t i = 0; i < n; i++) 15 | { 16 | int b = bills[i]; 17 | if (b == 5) 18 | five++; 19 | if (b == 10) 20 | { 21 | if (five <= 0) 22 | return false; 23 | ten++; 24 | five--; 25 | } 26 | if (b == 20) 27 | { 28 | if (ten > 0 && five > 0) 29 | { 30 | five--; 31 | ten--; 32 | } 33 | else if (five >= 3) 34 | five -= 3; 35 | else 36 | return false; 37 | } 38 | } 39 | return true; 40 | } 41 | }; 42 | // @lc code=end 43 | 44 | -------------------------------------------------------------------------------- /链表/114.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | void flatten(TreeNode* root) { 15 | if (root == nullptr) return; 16 | flatten(root->left); 17 | TreeNode* tmp = root->right; 18 | root->right = root->left; 19 | root->left = nullptr; 20 | flatten(tmp); 21 | while (root->right != nullptr) 22 | { 23 | root = root->right; 24 | } 25 | root->right = tmp; 26 | } 27 | }; -------------------------------------------------------------------------------- /链表/114.flatten-binary-tree-to-linked-list.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=114 lang=cpp 3 | * 4 | * [114] Flatten Binary Tree to Linked List 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution { 20 | public: 21 | void flatten(TreeNode* root) { 22 | if (root == nullptr) 23 | return; 24 | 25 | flatten(root->left); 26 | flatten(root->right); 27 | 28 | if (root->left == nullptr) 29 | return; 30 | 31 | TreeNode* last = root->left; 32 | while (last->right != nullptr) 33 | { 34 | last = last->right; 35 | } 36 | last->right = root->right; 37 | root->right = root->left; 38 | root->left = nullptr; 39 | } 40 | }; 41 | // @lc code=end 42 | 43 | -------------------------------------------------------------------------------- /链表/1290.二进制链表转整数.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=1290 lang=cpp 3 | * 4 | * [1290] 二进制链表转整数 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for singly-linked list. 10 | * struct ListNode { 11 | * int val; 12 | * ListNode *next; 13 | * ListNode() : val(0), next(nullptr) {} 14 | * ListNode(int x) : val(x), next(nullptr) {} 15 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | int getDecimalValue(ListNode* head) { 21 | int num = 0; 22 | while (head != nullptr) { 23 | num = (num << 1) + head->val; 24 | head = head->next; 25 | } 26 | return num; 27 | } 28 | }; 29 | // @lc code=end 30 | 31 | -------------------------------------------------------------------------------- /链表/148.排序链表.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=148 lang=cpp 3 | * 4 | * [148] 排序链表 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for singly-linked list. 10 | * struct ListNode { 11 | * int val; 12 | * ListNode *next; 13 | * ListNode() : val(0), next(nullptr) {} 14 | * ListNode(int x) : val(x), next(nullptr) {} 15 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | ListNode* sortList(ListNode* head) { 21 | if (head == nullptr) return head; 22 | vector v; 23 | ListNode* p = head; 24 | while (p != nullptr) 25 | { 26 | v.push_back(p->val); 27 | p = p->next; 28 | } 29 | sort(v.begin(), v.end()); 30 | p = head; 31 | for (auto c : v) 32 | { 33 | p->val = c; 34 | p = p->next; 35 | } 36 | return head; 37 | } 38 | }; 39 | // @lc code=end 40 | 41 | -------------------------------------------------------------------------------- /链表/1669.合并两个链表.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=1669 lang=cpp 3 | * 4 | * [1669] 合并两个链表 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for singly-linked list. 10 | * struct ListNode { 11 | * int val; 12 | * ListNode *next; 13 | * ListNode() : val(0), next(nullptr) {} 14 | * ListNode(int x) : val(x), next(nullptr) {} 15 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) { 21 | ListNode* p1 = list1; 22 | for (int i = 0; i < a - 1; i++) // a 的前一个节点 23 | p1 = p1->next; 24 | ListNode* pb = p1; 25 | for (int i = 0; i < b - a + 1; i++) // b节点 26 | pb = pb->next; 27 | ListNode* p2last = list2; 28 | while (p2last->next != nullptr) 29 | p2last = p2last->next; 30 | p1->next = list2; 31 | p2last->next =pb->next; 32 | return list1; 33 | } 34 | }; 35 | // @lc code=end 36 | 37 | -------------------------------------------------------------------------------- /链表/1721.交换链表中的节点.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=1721 lang=cpp 3 | * 4 | * [1721] 交换链表中的节点 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for singly-linked list. 10 | * struct ListNode { 11 | * int val; 12 | * ListNode *next; 13 | * ListNode() : val(0), next(nullptr) {} 14 | * ListNode(int x) : val(x), next(nullptr) {} 15 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | ListNode* swapNodes(ListNode* head, int k) { 21 | ListNode* dummy = new ListNode(); 22 | dummy->next = head; 23 | ListNode* p1 = dummy; 24 | for (int i = 0; i < k; i++) { 25 | p1 = p1->next; 26 | } 27 | ListNode* p2 = dummy; 28 | ListNode* fast = p1; 29 | while (fast != nullptr) { 30 | fast = fast->next; 31 | p2 = p2->next; 32 | } 33 | int t = p1->val; 34 | p1->val = p2->val; 35 | p2->val = t; 36 | return head; 37 | } 38 | }; 39 | // @lc code=end 40 | 41 | -------------------------------------------------------------------------------- /链表/203.移除链表元素.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=203 lang=cpp 3 | * 4 | * [203] 移除链表元素 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for singly-linked list. 10 | * struct ListNode { 11 | * int val; 12 | * ListNode *next; 13 | * ListNode() : val(0), next(nullptr) {} 14 | * ListNode(int x) : val(x), next(nullptr) {} 15 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | ListNode* removeElements(ListNode* head, int val) { 21 | // if (head == nullptr) return nullptr; 22 | ListNode* dummy = new ListNode(999); 23 | dummy->next = head; 24 | ListNode* p = dummy; 25 | while (head != nullptr) 26 | { 27 | if (head->val != val) 28 | { 29 | p->next = head; 30 | p = p->next; 31 | } 32 | head = head->next; 33 | p->next = nullptr; 34 | } 35 | return dummy->next; 36 | } 37 | }; 38 | // @lc code=end 39 | 40 | -------------------------------------------------------------------------------- /链表/2130.链表最大孪生和.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=2130 lang=cpp 3 | * 4 | * [2130] 链表最大孪生和 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for singly-linked list. 10 | * struct ListNode { 11 | * int val; 12 | * ListNode *next; 13 | * ListNode() : val(0), next(nullptr) {} 14 | * ListNode(int x) : val(x), next(nullptr) {} 15 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | int pairSum(ListNode* head) { 21 | vector memo; 22 | while (head != nullptr) { 23 | memo.push_back(head->val); 24 | head = head->next; 25 | } 26 | int maxsum = 0; 27 | int n = memo.size(); 28 | for (int i = 0; i < n / 2; i++) { 29 | maxsum = max(maxsum, memo[i] + memo[n - 1 - i]); 30 | } 31 | return maxsum; 32 | } 33 | }; 34 | // @lc code=end 35 | 36 | -------------------------------------------------------------------------------- /链表/2181.合并零之间的节点.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=2181 lang=cpp 3 | * 4 | * [2181] 合并零之间的节点 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for singly-linked list. 10 | * struct ListNode { 11 | * int val; 12 | * ListNode *next; 13 | * ListNode() : val(0), next(nullptr) {} 14 | * ListNode(int x) : val(x), next(nullptr) {} 15 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | ListNode* mergeNodes(ListNode* head) { 21 | ListNode* dummy = new ListNode(); 22 | ListNode* p = dummy; 23 | int sum = 0; 24 | while (head != nullptr) { 25 | sum += head->val; 26 | if (head->val == 0 && sum != 0) { 27 | p->next = new ListNode(sum); 28 | p = p->next; 29 | sum = 0; 30 | } 31 | head = head->next; 32 | } 33 | return dummy->next; 34 | } 35 | }; 36 | // @lc code=end 37 | 38 | -------------------------------------------------------------------------------- /链表/237.删除链表中的节点.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=237 lang=cpp 3 | * 4 | * [237] 删除链表中的节点 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for singly-linked list. 10 | * struct ListNode { 11 | * int val; 12 | * ListNode *next; 13 | * ListNode(int x) : val(x), next(NULL) {} 14 | * }; 15 | */ 16 | class Solution { 17 | public: 18 | void deleteNode(ListNode* node) { 19 | while (node->next != nullptr) 20 | { 21 | node->val = node->next->val; 22 | if (node->next->next == nullptr) 23 | { 24 | node->next = nullptr; 25 | return; 26 | } 27 | 28 | node = node->next; 29 | } 30 | } 31 | }; 32 | // @lc code=end 33 | 34 | -------------------------------------------------------------------------------- /链表/328.奇偶链表.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=328 lang=cpp 3 | * 4 | * [328] 奇偶链表 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for singly-linked list. 10 | * struct ListNode { 11 | * int val; 12 | * ListNode *next; 13 | * ListNode() : val(0), next(nullptr) {} 14 | * ListNode(int x) : val(x), next(nullptr) {} 15 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | ListNode* oddEvenList(ListNode* head) { 21 | if (head == nullptr || head->next == nullptr) 22 | return head; 23 | ListNode* odd = head; 24 | ListNode* even = head->next; 25 | ListNode* p1 = odd; 26 | ListNode* p2 = even; 27 | while (odd != nullptr && even != nullptr && odd->next != nullptr && even->next != nullptr) 28 | { 29 | cout << odd->val << " " << even->val << endl; 30 | odd->next = odd->next->next; 31 | even->next = even->next->next; 32 | odd = odd->next; 33 | even = even->next; 34 | } 35 | // 连接在一起 36 | odd->next = p2; 37 | return p1; 38 | } 39 | }; 40 | // @lc code=end 41 | 42 | -------------------------------------------------------------------------------- /链表/876.middle-of-the-linked-list.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=876 lang=cpp 3 | * 4 | * [876] Middle of the Linked List 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for singly-linked list. 10 | * struct ListNode { 11 | * int val; 12 | * ListNode *next; 13 | * ListNode() : val(0), next(nullptr) {} 14 | * ListNode(int x) : val(x), next(nullptr) {} 15 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | ListNode* middleNode(ListNode* head) { 21 | if (head == nullptr) 22 | return head; 23 | ListNode *fast, *slow; 24 | fast = slow = head; 25 | while (fast->next != nullptr && fast->next->next != nullptr) 26 | { 27 | fast = fast->next->next; 28 | slow = slow->next; 29 | } 30 | // 偶数个 31 | if (fast->next != nullptr && fast->next->next == nullptr) 32 | return slow->next; 33 | else 34 | return slow; 35 | } 36 | }; 37 | // @lc code=end 38 | 39 | -------------------------------------------------------------------------------- /链表/876.链表的中间结点.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode.cn id=876 lang=cpp 3 | * 4 | * [876] 链表的中间结点 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for singly-linked list. 10 | * struct ListNode { 11 | * int val; 12 | * ListNode *next; 13 | * ListNode() : val(0), next(nullptr) {} 14 | * ListNode(int x) : val(x), next(nullptr) {} 15 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | ListNode* middleNode(ListNode* head) { 21 | // ListNode* d = new ListNode(); 22 | // d->next = head; 23 | ListNode* fast = head; 24 | ListNode* slow = head; 25 | while (fast != nullptr && fast->next != nullptr) { 26 | slow = slow->next; 27 | fast = fast->next->next; 28 | } 29 | return slow; 30 | } 31 | }; 32 | // @lc code=end 33 | 34 | -------------------------------------------------------------------------------- /高频面试题/11.container-with-most-water.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=11 lang=cpp 3 | * 4 | * [11] Container With Most Water 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | int maxArea(vector& height) { 11 | int start = 0; 12 | int end = height.size() - 1; 13 | int val = 0; 14 | while (start <= end) 15 | { 16 | val = max(val, (end - start) * min(height[start], height[end])); 17 | if (height[start] < height[end]) 18 | start++; 19 | else 20 | end--; 21 | } 22 | return val; 23 | } 24 | }; 25 | // @lc code=end 26 | 27 | -------------------------------------------------------------------------------- /高频面试题/43.multiply-strings.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=43 lang=cpp 3 | * 4 | * [43] Multiply Strings 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | string multiply(string num1, string num2) { 11 | int n1 = num1.length(); 12 | int n2 = num2.length(); 13 | vector nums(n1 + n2); 14 | for (int i = num2.length()-1; i >= 0; i--) 15 | { 16 | for (int j = num1.length()-1; j >= 0; j--) 17 | { 18 | int a = num1[j] - '0'; 19 | int b = num2[i] - '0'; 20 | int r = a * b; 21 | r = nums[i + j + 1] + r; 22 | nums[i + j + 1] = r % 10; 23 | nums[i + j] = nums[i + j] + r / 10; 24 | } 25 | } 26 | int i = 0; 27 | while (i < nums.size() && nums[i] == 0) 28 | { 29 | i++; 30 | } 31 | string result = ""; 32 | while (i < nums.size() ) 33 | { 34 | result += (nums[i] + '0'); 35 | i++; 36 | } 37 | return result.size() == 0 ? "0" : result; 38 | } 39 | 40 | }; 41 | // @lc code=end 42 | 43 | -------------------------------------------------------------------------------- /高频面试题/659.split-array-into-consecutive-subsequences.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=659 lang=cpp 3 | * 4 | * [659] Split Array into Consecutive Subsequences 5 | */ 6 | 7 | // @lc code=start 8 | class Solution { 9 | public: 10 | bool isPossible(vector& nums) { 11 | // 122334 12 | unordered_map pool; 13 | unordered_map end; 14 | for (int i = 0; i < nums.size(); i++) 15 | { 16 | pool[nums[i]]++; 17 | } 18 | for (int i = 0; i < nums.size(); i++) 19 | { 20 | int val = nums[i]; 21 | if (pool[val] <= 0) continue; 22 | pool[val]--; 23 | if (end[val] > 0) // 放入某个子序列末尾 24 | { 25 | end[val]--; 26 | end[val+1]++; 27 | } 28 | else if (pool[val + 1] > 0 && pool[val + 2] > 0) // 有连续3张则能组成新子序列 29 | { 30 | pool[val + 1]--; 31 | pool[val + 2]--; 32 | end[val + 3]++; 33 | } 34 | else 35 | return false; 36 | } 37 | return true; 38 | } 39 | 40 | }; 41 | // @lc code=end 42 | 43 | --------------------------------------------------------------------------------