diff --git a/README.md b/README.md index 2e7daf5..a008d61 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成223道 +- leetcode练习,坚持每天一道,目前已完成275道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -10,27 +10,25 @@ - 网址:https://leetcode-cn.com/ ## 待解题目列表 -扫题:顺序 +剑指offer系列-持续多周,每周7题 -- [x] [65. 有效数字 -Hard](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_65_isNumber.java) +- [x] [剑指 Offer 16. 数值的整数次方](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_16_myPow.java) +- [x] [剑指 Offer 17. 打印从1到最大的n位数](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_17_printNumbers.java) +- [x] [剑指 Offer 18. 删除链表的节点](https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/) +- [ ] [剑指 Offer 19. 正则表达式匹配](https://leetcode-cn.com/problems/zheng-ze-biao-da-shi-pi-pei-lcof/) +- [ ] [剑指 Offer 20. 表示数值的字符串](https://leetcode-cn.com/problems/biao-shi-shu-zhi-de-zi-fu-chuan-lcof/) +- [ ] [剑指 Offer 21. 调整数组顺序使奇数位于偶数前面](https://leetcode-cn.com/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof/) +- [ ] [剑指 Offer 22. 链表中倒数第k个节点](https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/) -- [ ] [66. 加一 -Easy](https://leetcode-cn.com/problems/plus-one/) - -- [ ] [68. 文本左右对齐 -Hard](https://leetcode-cn.com/problems/text-justification/) - -- [ ] [73. 矩阵置零 -Medium](https://leetcode-cn.com/problems/set-matrix-zeroes/) - -- [ ] [74. 搜索二维矩阵 -Medium](https://leetcode-cn.com/problems/search-a-2d-matrix/) - -- [ ] [81. 搜索旋转排序数组 II -Medium](https://leetcode-cn.com/problems/search-in-rotated-sorted-array-ii/) +LCP -- [ ] [82. 删除排序链表中的重复元素 II -Medium](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/) +- [x] [LCP 06. 拿硬币](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/LCP/_6_minCount.java) ## 已解题目 > 20190404# leetcode目前已有题目1020道,免费852道 -### 题目类型(更新中) +### 题目类型(更新中...) - [数组]()(168) - [哈希表]()(102) @@ -59,9 +57,32 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成223) +### 题目列表(更新中—已完成275) -[Leetcode-Java(200+题解,持续更新、欢迎star)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_65_isNumber.java) +[Leetcode-Java(270+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_18_deleteNode.java) + +#### 剑指offer系列 + +| 题目 | 解决方案 | 相关话题 | 难度 | 备注 | +| ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ---- | +| [剑指 Offer 03. 数组中重复的数字](https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/) | [FindRepeatNumber](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_03_findRepeatNumber.java) | [数组]()、[哈希表]() | Easy | | +| [剑指 Offer 04. 二维数组中的查找](https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof/) | [FindNumberIn2DArray](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_04_findNumberIn2DArray.java) | [数组]()、[双指针]() | Easy | | +| [剑指 Offer 05. 替换空格](https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/) | [ReplaceSpace](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_05_replaceSpace.java) | | Easy | | +| [剑指 Offer 06. 从尾到头打印链表](https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/) | [ReversePrint](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_06_reversePrint.java) | [链表](https://leetcode-cn.com/tag/linked-list/) | Easy | | +| [剑指 Offer 07. 重建二叉树](https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/) | [BuildTree](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_07_buildTree.java) | [树](https://leetcode-cn.com/tag/tree/)、[DFS](https://leetcode-cn.com/tag/depth-first-search/) | Medium | | +| [剑指 Offer 09. 用两个栈实现队列](https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/) | [CQueue](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_09_CQueue.java) | [栈](https://leetcode-cn.com/tag/stack/)、[设计](https://leetcode-cn.com/tag/design/) | Easy | | +| [剑指 Offer 10- I. 斐波那契数列](https://leetcode-cn.com/problems/fei-bo-na-qi-shu-lie-lcof/) | [Fib](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_10_fib.java) | | Easy | | +| [剑指 Offer 10- II. 青蛙跳台阶问题](https://leetcode-cn.com/problems/qing-wa-tiao-tai-jie-wen-ti-lcof/) | [NumWays](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_10_2_numWays.java) | | Easy | | +| [剑指 Offer 11. 旋转数组的最小数字](https://leetcode-cn.com/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof/) | [MinArray](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_11_minArray.java) | [二分查找]() | Easy | | +| [剑指 Offer 12. 矩阵中的路径](https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/) | [Exist](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_12_exist.java) | [DFS](https://leetcode-cn.com/tag/depth-first-search/) | Medium | | +| [剑指 Offer 13. 机器人的运动范围](https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/) | [MovingCount](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_13_movingCount.java) | | Medium | | +| [剑指 Offer 14- I. 剪绳子](https://leetcode-cn.com/problems/jian-sheng-zi-lcof/) | [CuttingRope](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_14_1_cuttingRope.java) | [数学]()、[动态规划]() | Medium | | +| [剑指 Offer 15. 二进制中1的个数](https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/) | [HammingWeight](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_15_hammingWeight.java) | [位运算](https://leetcode-cn.com/tag/bit-manipulation/) | Easy | | +| [剑指 Offer 16. 数值的整数次方](https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof/) | [MyPow](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_16_myPow.java) | | Medium | | +| [剑指 Offer 17. 打印从1到最大的n位数](https://leetcode-cn.com/problems/da-yin-cong-1dao-zui-da-de-nwei-shu-lcof/) | [PrintNumbers](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_17_printNumbers.java) | [数学]() | Easy | | +| [剑指 Offer 18. 删除链表的节点](https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/) | [DeleteNode](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_18_deleteNode.java) | [链表](https://leetcode-cn.com/tag/linked-list/) | Easy | | + +#### 经典题解 | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -130,34 +151,60 @@ | #63 | [不同路径 II](https://leetcode-cn.com/problems/unique-paths-ii/) | [UniquePathsWithObstacles](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_63_uniquePathsWithObstacles.java) | [数组]()、[动态规划]() | Medium | | | #64 | [最小路径和](https://leetcode-cn.com/problems/minimum-path-sum/) | [MinPathSum](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_64_minPathSum.java) | [数组]()、[动态规划]() | Medium | | | #65 | [有效数字](https://leetcode-cn.com/problems/valid-number/) | [IsNumber](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_65_isNumber.java) | [数组]()、[字符串]() | Hard | | +| #66 | [加一](https://leetcode-cn.com/problems/plus-one/) | [PlusOne](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_66_plusOne.java) | [数组]() | Easy | | +| #67 | [二进制求和](https://leetcode-cn.com/problems/add-binary/) | [AddBinary](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_67_addBinary.java) | [数学]()、[字符串]() | Easy | | +| #68 | [文本左右对齐](https://leetcode-cn.com/problems/text-justification/) | [FullJustify](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_68_fullJustify.java) | [字符串]() | Hard | | | #69 | [x 的平方根](https://leetcode-cn.com/problems/sqrtx/) | [MySqrt](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_69_mySqrt.java) | [数学]()、[二分查找]() | Easy | | | #70 | [爬楼梯](https://leetcode-cn.com/problems/climbing-stairs/) | [ClimbStairs](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_70_climbStairs.java) | [动态规划]() | Easy | 经典题 | | #71 | [简化路径](https://leetcode-cn.com/problems/simplify-path/) | [SimplifyPath](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_71_simplifyPath.java) | [栈](https://leetcode-cn.com/tag/stack/)、[字符串]() | Medium | | | #72 | [编辑距离](https://leetcode-cn.com/problems/edit-distance/) | [MinDistance](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_72_minDistance.java) | [字符串]()、[动态规划]() | Hard | | +| #73 | [矩阵置零](https://leetcode-cn.com/problems/set-matrix-zeroes/) | [SetZeroes](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_73_setZeroes.java) | [数组]() | Medium | | +| #74 | [搜索二维矩阵](https://leetcode-cn.com/problems/search-a-2d-matrix/) | [SearchMatrix](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_74_searchMatrix.java) | [数组]()、[二分查找]() | Medium | | | #75 | [颜色分类](https://leetcode-cn.com/problems/sort-colors/) | [SortColors](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_75_sortColors.java) | [排序](https://leetcode-cn.com/tag/sort/)、[数组]()、[双指针]() | Medium | | | #76 | [最小覆盖子串](https://leetcode-cn.com/problems/minimum-window-substring/) | [MinWindow](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_76_minWindow.java) | [哈希表]()、[双指针]()、[字符串]()、[sliding window]() | Hard | | | #77 | [组合](https://leetcode-cn.com/problems/combinations/) | [Combine](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_77_combine.java) | [回溯算法]() | Medium | | | #78 | [子集](https://leetcode-cn.com/problems/subsets/) | [Subsets](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_78_subsets.java) | [位运算](https://leetcode-cn.com/tag/bit-manipulation/)、[数组]()、[回溯算法]() | Medium | | | #79 | [单词搜索](https://leetcode-cn.com/problems/word-search/) | [Exist](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_79_exist.java) | [数组]()、[回溯算法]() | Medium | 经典题(回溯) | | #80 | [删除排序数组中的重复项 II](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array-ii/) | [RemoveDuplicates](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_80_removeDuplicates.java) | [数组]()、[双指针]() | Medium | | +| #81 | [搜索旋转排序数组 II](https://leetcode-cn.com/problems/search-in-rotated-sorted-array-ii/) | [Search](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_81_search.java) | [数组]()、[二分查找]() | Medium | | +| #82 | [删除排序链表中的重复元素 II](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/) | [DeleteDuplicates](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_82_deleteDuplicates.java) | [链表](https://leetcode-cn.com/tag/linked-list/) | Medium | | +| #83 | [删除排序链表中的重复元素](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/) | [DeleteDuplicates](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_83_deleteDuplicates.java) | [链表](https://leetcode-cn.com/tag/linked-list/) | Easy | | | #84 | [柱状图中最大的矩形](https://leetcode-cn.com/problems/largest-rectangle-in-histogram/) | [LargestRectangleArea](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_84_largestRectangleArea.java) | [栈](https://leetcode-cn.com/tag/stack/)、[数组]() | Hard | 经典题(栈、分治) | | #85 | [最大矩形](https://leetcode-cn.com/problems/maximal-rectangle/) | [MaximalRectangle](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_85_maximalRectangle.java) | [栈](https://leetcode-cn.com/tag/stack/)、[数组]() | Hard | | | #86 | [分隔链表](https://leetcode-cn.com/problems/partition-list/) | [Partition](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_86_Partition.java) | [链表](https://leetcode-cn.com/tag/linked-list/)、[双指针]() | Medium | | +| #87 | [扰乱字符串](https://leetcode-cn.com/problems/scramble-string/) | [IsScramble](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_87_isScramble.java) | [字符串]()、[动态规划]() | Hard | | +| #88 | [合并两个有序数组](https://leetcode-cn.com/problems/merge-sorted-array/) | [Merge](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_88_merge.java) | [数组]()、[双指针]() | Easy | | +| #89 | [格雷编码](https://leetcode-cn.com/problems/gray-code/) | [GrayCode](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_89_grayCode.java) | [回溯算法]() | Medium | | | #90 | [子集 II](https://leetcode-cn.com/problems/subsets-ii/) | [SubsetsWithDup](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_90_subsetsWithDup.java) | [数组]()、[回溯算法]() | Medium | | | #91 | [解码方法](https://leetcode-cn.com/problems/decode-ways/) | [NumDecodings](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_91_numDecodings.java) | [字符串]()、[动态规划]() | Medium | | | #92 | [反转链表 II](https://leetcode-cn.com/problems/reverse-linked-list-ii/) | [ReverseBetween](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_92_ReverseBetween.java) | [链表](https://leetcode-cn.com/tag/linked-list/) | Medium | | | #93 | [复原IP地址](https://leetcode-cn.com/problems/restore-ip-addresses/) | [RestoreIpAddresses](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_93_restoreIpAddresses.java) | [字符串]()、[回溯算法]() | Medium | | | #94 | [二叉树的中序遍历](https://leetcode-cn.com/problems/binary-tree-inorder-traversal/) | [InorderTraversal](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_94_inorderTraversal.java) | [栈](https://leetcode-cn.com/tag/stack/)、[树](https://leetcode-cn.com/tag/tree/)、[哈希表]() | Medium | | | #95 | [不同的二叉搜索树 II](https://leetcode-cn.com/problems/unique-binary-search-trees-ii/) | [GenerateTrees](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_95_generateTrees.java) | [树](https://leetcode-cn.com/tag/tree/)、[动态规划]() | Medium | DP实现未想到 | +| #96 | [不同的二叉搜索树](https://leetcode-cn.com/problems/unique-binary-search-trees/) | [NumTrees](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_96_numTrees.java) | [树](https://leetcode-cn.com/tag/tree/)、[动态规划]() | Medium | | +| #97 | [交错字符串](https://leetcode-cn.com/problems/interleaving-string/) | [IsInterleave](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_97_isInterleave.java) | [字符串]()、[动态规划]() | Hard | | | #98 | [验证二叉搜索树](https://leetcode-cn.com/problems/validate-binary-search-tree/) | [IsValidBST](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_98_isValidBST.java) | [树](https://leetcode-cn.com/tag/tree/)、[DFS](https://leetcode-cn.com/tag/depth-first-search/) | Medium | | +| #99 | [恢复二叉搜索树](https://leetcode-cn.com/problems/recover-binary-search-tree/) | [RecoverTree](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_99_recoverTree.java) | [树](https://leetcode-cn.com/tag/tree/)、[DFS](https://leetcode-cn.com/tag/depth-first-search/) | Hard | | +| #100 | [相同的树](https://leetcode-cn.com/problems/same-tree/) | [IsSameTree](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_100_isSameTree.java) | [树](https://leetcode-cn.com/tag/tree/)、[DFS](https://leetcode-cn.com/tag/depth-first-search/) | Easy | | | #101 | [对称二叉树](https://leetcode-cn.com/problems/symmetric-tree/) | [IsSymmetric](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_101_isSymmetric.java) | [树](https://leetcode-cn.com/tag/tree/)、[DFS](https://leetcode-cn.com/tag/depth-first-search/)、[BFS](https://leetcode-cn.com/tag/breadth-first-search/) | Easy | | | #102 | [二叉树的层次遍历](https://leetcode-cn.com/problems/binary-tree-level-order-traversal/) | [LevelOrder](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_102_levelOrder.java) | [树](https://leetcode-cn.com/tag/tree/)、[BFS](https://leetcode-cn.com/tag/breadth-first-search/) | Medium | | | #103 | [二叉树的锯齿形层次遍历](https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/) | [ZigzagLevelOrder](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_103_zigzagLevelOrder.java) | [栈](https://leetcode-cn.com/tag/stack/)、[树](https://leetcode-cn.com/tag/tree/)、[BFS](https://leetcode-cn.com/tag/breadth-first-search/) | Medium | | | #104 | [二叉树的最大深度](https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/) | [MaxDepth](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_104_maxDepth.java) | [树](https://leetcode-cn.com/tag/tree/)、[DFS](https://leetcode-cn.com/tag/depth-first-search/) | Easy | | | #105 | [从前序与中序遍历序列构造二叉树](https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) | [BuildTree](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_105_buildTree.java) | [树](https://leetcode-cn.com/tag/tree/)、[DFS](https://leetcode-cn.com/tag/depth-first-search/)、[数组]() | Medium | | +| #106 | [从中序与后序遍历序列构造二叉树](https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/) | [BuildTree](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_106_buildTree.java) | [树](https://leetcode-cn.com/tag/tree/)、[DFS](https://leetcode-cn.com/tag/depth-first-search/)、[数组]() | Medium | | +| #107 | [二叉树的层次遍历 II](https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/) | [LevelOrderBottom](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_107_levelOrderBottom.java) | [树](https://leetcode-cn.com/tag/tree/)、[BFS](https://leetcode-cn.com/tag/breadth-first-search/) | Easy | | | #108 | [将有序数组转换为二叉搜索树](https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/) | [SortedArrayToBST](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_108_sortedArrayToBST.java) | [树](https://leetcode-cn.com/tag/tree/)、[DFS](https://leetcode-cn.com/tag/depth-first-search/) | Easy | | +| #109 | [有序链表转换二叉搜索树](https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree/) | [SortedListToBST](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_109_sortedListToBST.java) | [DFS](https://leetcode-cn.com/tag/depth-first-search/)、[链表](https://leetcode-cn.com/tag/linked-list/) | Medium | | +| #110 | [平衡二叉树](https://leetcode-cn.com/problems/balanced-binary-tree/) | [IsBalanced](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_110_isBalanced.java) | [树](https://leetcode-cn.com/tag/tree/)、[DFS](https://leetcode-cn.com/tag/depth-first-search/) | Easy | | +| #111 | [二叉树的最小深度](https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/) | [MinDepth](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_111_minDepth.java) | [树](https://leetcode-cn.com/tag/tree/)、[DFS](https://leetcode-cn.com/tag/depth-first-search/) | Easy | | +| #112 | [路径总和](https://leetcode-cn.com/problems/path-sum/) | [HasPathSum](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_112_hasPathSum.java) | [树](https://leetcode-cn.com/tag/tree/)、[DFS](https://leetcode-cn.com/tag/depth-first-search/) | Easy | | | #113 | [路径总和 II](https://leetcode-cn.com/problems/path-sum-ii/) | [PathSum](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_113_pathSum.java) | [树](https://leetcode-cn.com/tag/tree/)、[DFS](https://leetcode-cn.com/tag/depth-first-search/) | Medium | | | #114 | [二叉树展开为链表](https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/) | [Flatten](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_114_flatten.java) | [树](https://leetcode-cn.com/tag/tree/)、[DFS](https://leetcode-cn.com/tag/depth-first-search/) | Medium | | +| #115 | [不同的子序列](https://leetcode-cn.com/problems/distinct-subsequences/) | [NumDistinct](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_115_numDistinct.java) | [字符串]()、[动态规划]() | Hard | | +| #116 | [填充每个节点的下一个右侧节点指针](https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/) | [Connect](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_116_connect.java) | [树](https://leetcode-cn.com/tag/tree/)、[DFS](https://leetcode-cn.com/tag/depth-first-search/) | Medium | | +| #117 | [填充每个节点的下一个右侧节点指针 II](https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii/) | [Connect](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_117_connect.java) | [树](https://leetcode-cn.com/tag/tree/)、[DFS](https://leetcode-cn.com/tag/depth-first-search/) | Medium | | +| #118 | [杨辉三角](https://leetcode-cn.com/problems/pascals-triangle/) | [Generate](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_118_generate.java) | [数组]() | Easy | | +| #119 | [杨辉三角 II](https://leetcode-cn.com/problems/pascals-triangle-ii/) | [GetRow](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_119_getRow.java) | [数组]() | Easy | | | #120 | [三角形最小路径和](https://leetcode-cn.com/problems/triangle/) | [MinimumTotal](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_120_minimumTotal.java) | [数组]()、[动态规划]() | Medium | | | #121 | [买卖股票的最佳时机](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/) | [MaxProfit](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_121_maxProfit.java) | [数组]()、[动态规划]() | Easy | | | #122 | [买卖股票的最佳时机 II](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/) | [MaxProfit](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_122_maxProfit.java) | [贪心算法](https://leetcode-cn.com/tag/greedy/)、[数组]() | Easy | | @@ -167,6 +214,11 @@ | #126 | [单词接龙 II](https://leetcode-cn.com/problems/word-ladder-ii/) | [FindLadders](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_126_findLadders.java) | [BFS](https://leetcode-cn.com/tag/breadth-first-search/)、[数组]()、[字符串]()、[回溯算法]() | Hard | | | #127 | [单词接龙](https://leetcode-cn.com/problems/word-ladder/) | [LadderLength](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_127_ladderLength_2.java) | [BFS](https://leetcode-cn.com/tag/breadth-first-search/) | Medium | [自己原始解法](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_127_ladderLength.java) | | #128 | [最长连续序列](https://leetcode-cn.com/problems/longest-consecutive-sequence/) | [LongestConsecutive](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_128_longestConsecutive.java) | [并查集](https://leetcode-cn.com/tag/union-find/)、[数组]() | Hard | | +| #129 | [求根到叶子节点数字之和](https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/) | [SumNumbers](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_129_sumNumbers.java) | [树](https://leetcode-cn.com/tag/tree/)、[DFS](https://leetcode-cn.com/tag/depth-first-search/) | Medium | | +| #130 | [被围绕的区域](https://leetcode-cn.com/problems/surrounded-regions/) | [Solve](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_130_solve.java) | [BFS](https://leetcode-cn.com/tag/breadth-first-search/)、[DFS](https://leetcode-cn.com/tag/depth-first-search/)、[并查集](https://leetcode-cn.com/tag/union-find/) | Medium | | +| #131 | [分割回文串](https://leetcode-cn.com/problems/palindrome-partitioning/) | [Partition](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_131_partition.java) | [回溯算法]() | Medium | | +| #132 | [分割回文串 II](https://leetcode-cn.com/problems/palindrome-partitioning-ii/) | [MinCut](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_132_minCut.java) | [动态规划]() | Hard | | +| #133 | [克隆图](https://leetcode-cn.com/problems/clone-graph/) | [CloneGraph](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_133_cloneGraph.java) | [BFS](https://leetcode-cn.com/tag/breadth-first-search/)、[DFS](https://leetcode-cn.com/tag/depth-first-search/)、[图](https://leetcode-cn.com/tag/graph/) | Medium | | | #136 | [只出现一次的数字](https://leetcode-cn.com/problems/single-number/) | [SingleNumber](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_136_singleNumber.java) | [哈希表]()、[位运算](https://leetcode-cn.com/tag/bit-manipulation/) | Easy | 位运算了解下 | | #138 | [复制带随机指针的链表](https://leetcode-cn.com/problems/copy-list-with-random-pointer/) | [CopyRandomList](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_138_CopyRandomList.java) | [哈希表]()、[链表](https://leetcode-cn.com/tag/linked-list/) | Medium | | | #139 | [单词拆分](https://leetcode-cn.com/problems/word-break/) | [WordBreak](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_139_wordBreak.java) | [动态规划]() | Medium | 回溯实现耗时 | @@ -277,14 +329,21 @@ | #1052 | [爱生气的书店老板](https://leetcode-cn.com/problems/grumpy-bookstore-owner/) | [MaxSatisfied](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1052_maxSatisfied.java) | [数组]()、[sliding window]() | Medium | | | #1053 | [交换一次的先前排列](https://leetcode-cn.com/problems/previous-permutation-with-one-swap/) | [PrevPermOpt](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1053_prevPermOpt1.java) | [贪心算法](https://leetcode-cn.com/tag/greedy/)、[数组]() | Medium | | | #1054 | [距离相等的条形码](https://leetcode-cn.com/problems/distant-barcodes/) | [RearrangeBarcodes](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1054_rearrangeBarcodes.java) | [堆](https://leetcode-cn.com/tag/heap/)、[排序](https://leetcode-cn.com/tag/sort/) | Medium | | +| #1114 | [按序打印](https://leetcode-cn.com/problems/print-in-order/) | [Foo](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1114_Foo.java) | | Easy | | +| #1115 | [交替打印FooBar](https://leetcode-cn.com/problems/print-foobar-alternately/) | [FooBar]([Leetcode-Java(250+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1115_FooBar.java)) | | Medium | | +| #1116 | [打印零与奇偶数](https://leetcode-cn.com/problems/print-zero-even-odd/) | [ZeroEvenOdd](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1116_ZeroEvenOdd.java) | | Medium | | +| #1117 | [H2O 生成](https://leetcode-cn.com/problems/building-h2o/) | [H2O](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1117_H2O.java) | | Medium | | +| #1195 | [交替打印字符串](https://leetcode-cn.com/problems/fizz-buzz-multithreaded/) | [FizzBuzz](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1195_FizzBuzz.java) | | Medium | | +| #1226 | [哲学家进餐](https://leetcode-cn.com/problems/the-dining-philosophers/) | [DiningPhilosophers](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1226_DiningPhilosophers.java) | | Medium | | -LCP +#### LCP -| No | 题目 | 解决方案 | 难度 | -| ---- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | -| #1 | [LCP 1. 猜数字](https://leetcode-cn.com/problems/guess-numbers/) | [Game](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/LCP/_1_game.java) | Easy | -| #2 | [LCP 2. 分式化简](https://leetcode-cn.com/problems/deep-dark-fraction/) | [Fraction](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/LCP/_2_fraction.java) | Easy | -| #3 | [LCP 3. 机器人大冒险](https://leetcode-cn.com/problems/programmable-robot/) | [Robot](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/LCP/_3_robot.java) | Medium | -| #4 | [LCP 4. 覆盖](https://leetcode-cn.com/problems/broken-board-dominoes/) | [Domino](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/LCP/_4_domino.java) | Hard | -| #5 | [LCP 5. 发 LeetCoin](https://leetcode-cn.com/problems/coin-bonus/) | [Bonus](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/LCP/_5_bonus_2.java) | Hard | +| 题目 | 解决方案 | 难度 | 备注 | +| ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ---- | +| [LCP 1. 猜数字](https://leetcode-cn.com/problems/guess-numbers/) | [Game](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/LCP/_1_game.java) | Easy | | +| [LCP 2. 分式化简](https://leetcode-cn.com/problems/deep-dark-fraction/) | [Fraction](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/LCP/_2_fraction.java) | Easy | | +| [LCP 3. 机器人大冒险](https://leetcode-cn.com/problems/programmable-robot/) | [Robot](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/LCP/_3_robot.java) | Medium | | +| [LCP 4. 覆盖](https://leetcode-cn.com/problems/broken-board-dominoes/) | [Domino](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/LCP/_4_domino.java) | Hard | | +| [LCP 5. 发 LeetCoin](https://leetcode-cn.com/problems/coin-bonus/) | [Bonus](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/LCP/_5_bonus_2.java) | Hard | | +| [LCP 06. 拿硬币](https://leetcode-cn.com/problems/na-ying-bi/) | [MinCount](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/LCP/_6_minCount.java) | Easy | | diff --git a/src/pp/arithmetic/LCP/_6_minCount.java b/src/pp/arithmetic/LCP/_6_minCount.java new file mode 100644 index 0000000..6176961 --- /dev/null +++ b/src/pp/arithmetic/LCP/_6_minCount.java @@ -0,0 +1,62 @@ +package pp.arithmetic.LCP; + +/** + * Created by wangpeng on 2020-09-02. + * LCP 06. 拿硬币 + *

+ * 桌上有 n 堆力扣币,每堆的数量保存在数组 coins 中。我们每次可以选择任意一堆,拿走其中的一枚或者两枚,求拿完所有力扣币的最少次数。 + *

+ * 示例 1: + *

+ * 输入:[4,2,1] + *

+ * 输出:4 + *

+ * 解释:第一堆力扣币最少需要拿 2 次,第二堆最少需要拿 1 次,第三堆最少需要拿 1 次,总共 4 次即可拿完。 + *

+ * 示例 2: + *

+ * 输入:[2,3,10] + *

+ * 输出:8 + *

+ * 限制: + *

+ * 1 <= n <= 4 + * 1 <= coins[i] <= 10 + *

+ * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/na-ying-bi + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _6_minCount { + + public static void main(String[] args) { + _6_minCount minCount = new _6_minCount(); + System.out.println(minCount.minCount(new int[]{4, 2, 1})); + System.out.println(minCount.minCount(new int[]{2, 3, 10})); + + } + + /** + * 解题思路: + * 需要最少次数,利用贪心的思路,每次尽可能的多拿(也就是2个) + * + * @param coins + * @return + */ + public int minCount(int[] coins) { + if (coins == null) return 0; + int retVal = 0; + for (int i = 0; i < coins.length; i++) { + int coin = coins[i]; + if (coin % 2 == 0) { + retVal += coin / 2; + } else { + retVal += coin / 2 + 1; + } + } + + return retVal; + } +} diff --git a/src/pp/arithmetic/Util.java b/src/pp/arithmetic/Util.java index 9999552..7e38661 100644 --- a/src/pp/arithmetic/Util.java +++ b/src/pp/arithmetic/Util.java @@ -4,7 +4,9 @@ import pp.arithmetic.model.ListNode; import pp.arithmetic.model.TreeNode; +import java.util.ArrayDeque; import java.util.List; +import java.util.Queue; import java.util.Random; /** @@ -102,6 +104,35 @@ public static TreeNode generateTreeNode() { return root; } + public static TreeNode generateTreeNode(Integer[] nodes) { + if (nodes == null || nodes.length == 0 || nodes[0] == null) return null; + TreeNode root = new TreeNode(nodes[0]); + Queue stack = new ArrayDeque<>(); + stack.add(root); + int length = 1; + while (length < nodes.length) { + TreeNode poll = stack.poll(); + if (poll == null) break; + Integer node = nodes[length]; + if (node!=null) { + TreeNode left = new TreeNode(node); + poll.left = left; + stack.add(left); + } + length++; + if (length < nodes.length) { + node=nodes[length]; + if (node!=null) { + TreeNode right = new TreeNode(node); + poll.right = right; + stack.add(right); + } + length++; + } + } + return root; + } + public static void printArray(int[] nums) { for (int i = 0; i < nums.length; i++) { System.out.print(nums[i] + " "); @@ -116,6 +147,17 @@ public static void printList(List nums) { System.out.println(); } + public static void printLists(List> lists) { + for (int i = 0; i < lists.size(); i++) { + System.out.print("[ "); + for (int j = 0; j < lists.get(i).size(); j++) { + System.out.print(lists.get(i).get(j) + " "); + } + System.out.print("]"); + System.out.println(); + } + } + public static void printStringList(List nums) { if (nums == null){ System.out.println("list is null"); @@ -126,7 +168,7 @@ public static void printStringList(List nums) { return; } for (int i = 0; i < nums.size(); i++) { - System.out.print(nums.get(i) + " "); + System.out.println(nums.get(i)); } System.out.println(); } diff --git a/src/pp/arithmetic/leetcode/_100_isSameTree.java b/src/pp/arithmetic/leetcode/_100_isSameTree.java new file mode 100644 index 0000000..9e65ab0 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_100_isSameTree.java @@ -0,0 +1,75 @@ +package pp.arithmetic.leetcode; + +import pp.arithmetic.model.TreeNode; + +/** + * Created by wangpeng on 2019-12-04. + * 100. 相同的树 + * + * 给定两个二叉树,编写一个函数来检验它们是否相同。 + * + * 如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。 + * + * 示例 1: + * + * 输入: 1 1 + * / \ / \ + * 2 3 2 3 + * + * [1,2,3], [1,2,3] + * + * 输出: true + * 示例 2: + * + * 输入: 1 1 + * / \ + * 2 2 + * + * [1,2], [1,null,2] + * + * 输出: false + * 示例 3: + * + * 输入: 1 1 + * / \ / \ + * 2 1 1 2 + * + * [1,2,1], [1,1,2] + * + * 输出: false + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/same-tree + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _100_isSameTree { + + public static void main(String[] args) { + _100_isSameTree isSameTree = new _100_isSameTree(); + TreeNode p = new TreeNode(1); + p.left = new TreeNode(2); + p.right = new TreeNode(3); + TreeNode q = new TreeNode(1); + q.left = new TreeNode(2); +// q.right = new TreeNode(3); + + System.out.println(isSameTree.isSameTree(p,q)); + } + + /** + * 解题思路: + * 典型的树的深度遍历(DFS) + * 1、判断左子树是否相同 + * 2、判断右子树是否相同 + * 3、判断父节点是否相同 + * + * @param p + * @param q + * @return + */ + public boolean isSameTree(TreeNode p, TreeNode q) { + if (p== null && q == null) return true; + if (p == null || q == null) return false; + return isSameTree(p.left,q.left) && isSameTree(p.right,q.right) && p.val == q.val; + } +} diff --git a/src/pp/arithmetic/leetcode/_106_buildTree.java b/src/pp/arithmetic/leetcode/_106_buildTree.java new file mode 100644 index 0000000..5a3d6dc --- /dev/null +++ b/src/pp/arithmetic/leetcode/_106_buildTree.java @@ -0,0 +1,74 @@ +package pp.arithmetic.leetcode; + +import pp.arithmetic.Util; +import pp.arithmetic.model.TreeNode; + +import java.util.Arrays; + +/** + * Created by wangpeng on 2019-12-09. + * 106. 从中序与后序遍历序列构造二叉树 + * + * 根据一棵树的中序遍历与后序遍历构造二叉树。 + * + * 注意: + * 你可以假设树中没有重复的元素。 + * + * 例如,给出 + * + * 中序遍历 inorder = [9,3,15,20,7] + * 后序遍历 postorder = [9,15,7,20,3] + * 返回如下的二叉树: + * + * 3 + * / \ + * 9 20 + * / \ + * 15 7 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _106_buildTree { + + public static void main(String[] args) { + _106_buildTree buildTree = new _106_buildTree(); + TreeNode treeNode = buildTree.buildTree(new int[]{9, 3, 15, 20, 7}, new int[]{9, 15, 7, 20, 3}); + Util.printTree(treeNode); + } + + /** + * 解题思路: + * 中序:左->中->右,后序:左->右->中 + * 1、取后序的最后一位就是根节点 + * 2、遍历中序,找到根节点在中序中的位置I,I左边的就是左子树,右边就是右子树 + * 3、分别取中序和后续的0-I位置,得到的就是左子树的中序和后续遍历接通,重复步骤1、2将左子树构造出来 + * 4、同理步骤3,将右子树构造出来 + * + * 执行用时 :19 ms, 在所有 java 提交中击败了29.64%的用户 + * 内存消耗 :77.3 MB, 在所有 java 提交中击败了5.17%的用户 + * + * 用时耗时优化建议:Arrays.copy可以转换为数组的index下标遍历 + * + * @param inorder + * @param postorder + * @return + */ + public TreeNode buildTree(int[] inorder, int[] postorder) { + if (inorder.length == 0) return null; + int rootVal = postorder[postorder.length - 1]; + TreeNode rootNode = new TreeNode(rootVal); + int rootIndex = 0; + for (int i = 0; i < inorder.length; i++) { + if (inorder[i] == rootVal){ + rootIndex = i; + break; + } + } + rootNode.left = buildTree(Arrays.copyOfRange(inorder, 0, rootIndex), Arrays.copyOfRange(postorder, 0, rootIndex)); + rootNode.right = buildTree(Arrays.copyOfRange(inorder, rootIndex + 1, inorder.length), Arrays.copyOfRange(postorder, rootIndex, postorder.length - 1)); + return rootNode; + } + +} diff --git a/src/pp/arithmetic/leetcode/_107_levelOrderBottom.java b/src/pp/arithmetic/leetcode/_107_levelOrderBottom.java new file mode 100644 index 0000000..5f080b4 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_107_levelOrderBottom.java @@ -0,0 +1,84 @@ +package pp.arithmetic.leetcode; + +import pp.arithmetic.Util; +import pp.arithmetic.model.TreeNode; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.List; +import java.util.Queue; + +/** + * Created by wangpeng on 2019-12-10. + * 107. 二叉树的层次遍历 II + * + * 给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历) + * + * 例如: + * 给定二叉树 [3,9,20,null,null,15,7], + * + * 3 + * / \ + * 9 20 + * / \ + * 15 7 + * 返回其自底向上的层次遍历为: + * + * [ + * [15,7], + * [9,20], + * [3] + * ] + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _107_levelOrderBottom { + + public static void main(String[] args) { + _107_levelOrderBottom levelOrderBottom = new _107_levelOrderBottom(); + TreeNode node = new TreeNode(3); + node.left = new TreeNode(9); + node.right = new TreeNode(20); + node.right.left = new TreeNode(15); + node.right.right = new TreeNode(7); + List> lists = levelOrderBottom.levelOrderBottom(node); + for (int i = 0; i < lists.size(); i++) { + Util.printList(lists.get(i)); + } + } + + /** + * 解题思路: + * 树的问题就是遍历,本题用树的广度遍历(BFS) + * BFS遍历依赖队列保存一层的节点 + * + * @param root + * @return + */ + public List> levelOrderBottom(TreeNode root) { + List> retList = new ArrayList<>(); + if (root == null) return retList; + Queue queue = new ArrayDeque<>(); + queue.add(root); + while (queue.peek() != null) { + List items = new ArrayList<>(); + List treeList = new ArrayList<>(); + TreeNode poll = queue.poll(); + while (poll != null) { + items.add(poll.val); + if (poll.left != null) treeList.add(poll.left); + if (poll.right != null) treeList.add(poll.right); + poll = queue.poll(); + } + if (!treeList.isEmpty()) { + queue.addAll(treeList); + } + if (!items.isEmpty()) { + retList.add(0, items); + } + } + return retList; + } +} diff --git a/src/pp/arithmetic/leetcode/_109_sortedListToBST.java b/src/pp/arithmetic/leetcode/_109_sortedListToBST.java new file mode 100644 index 0000000..73355f2 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_109_sortedListToBST.java @@ -0,0 +1,91 @@ +package pp.arithmetic.leetcode; + +import pp.arithmetic.Util; +import pp.arithmetic.model.ListNode; +import pp.arithmetic.model.TreeNode; + +/** + * Created by wangpeng on 2019-12-11. + * 109. 有序链表转换二叉搜索树 + * + * 给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。 + * + * 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。 + * + * 示例: + * + * 给定的有序链表: [-10, -3, 0, 5, 9], + * + * 一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树: + * + * 0 + * / \ + * -3 9 + * / / + * -10 5 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _109_sortedListToBST { + + public static void main(String[] args) { + _109_sortedListToBST sortedListToBST = new _109_sortedListToBST(); + ListNode listNode = new ListNode(-10); + listNode.next = new ListNode(-3); + listNode.next.next = new ListNode(0); + listNode.next.next.next = new ListNode(5); + listNode.next.next.next.next = new ListNode(9); + TreeNode treeNode = sortedListToBST.sortedListToBST(listNode); + Util.printTree(treeNode); + } + + /** + * 解题思路: + * 去有序链表的中间位置作为根节点,将左部生成左子树,右部生成右子树 + * 难点: + * 1、如何找到链表的中间位置 ==> 两次遍历,第一次使用length记录总长度,第二次取length/2的位置为更觉得 + * 2、如何将一个链表分割成左右两部分独立链表 ==> 变量rightPreNode保存遍历过程中的前置节点,为断链做准备 + * + * 对于难点一:也可以用快慢指针定位中间位置 + * + * 链表的解法多数是遍历,利用额外的节点保存中间状态 + * 树的解法多数是递归,同样的入参生成左右子树 + * + * 执行用时 :2 ms, 在所有 java 提交中击败了48.48%的用户 + * 内存消耗 :38.7 MB , 在所有 java 提交中击败了97.64%的用户 + * + * @param head + * @return + */ + public TreeNode sortedListToBST(ListNode head) { + if (head == null) return null; + ListNode next = head; + int length = 0; + while (next!=null){ + length++; + next = next.next; + } + if (length==1){ + return new TreeNode(head.val); + } + ListNode leftNode = head; + ListNode rightNode = head; + ListNode rightPreNode = head; + for (int i = 0; i < length / 2; i++) { + rightPreNode = rightNode; + rightNode = rightPreNode.next; + } + //生成根节点 + TreeNode root = new TreeNode(rightNode.val); + //断开左侧 + rightPreNode.next = null; + //断开右侧 + rightNode = rightNode.next; + //生成左右子树 + root.left = sortedListToBST(leftNode); + root.right = sortedListToBST(rightNode); + return root; + } +} diff --git a/src/pp/arithmetic/leetcode/_110_isBalanced.java b/src/pp/arithmetic/leetcode/_110_isBalanced.java new file mode 100644 index 0000000..ba22318 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_110_isBalanced.java @@ -0,0 +1,73 @@ +package pp.arithmetic.leetcode; + +import javafx.util.Pair; +import pp.arithmetic.Util; +import pp.arithmetic.model.TreeNode; + +/** + * Created by wangpeng on 2019-12-12. + * 110. 平衡二叉树 + * + * 给定一个二叉树,判断它是否是高度平衡的二叉树。 + * + * 本题中,一棵高度平衡二叉树定义为: + * + * 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。 + * + * 示例 1: + * + * 给定二叉树 [3,9,20,null,null,15,7] + * + * 3 + * / \ + * 9 20 + * / \ + * 15 7 + * 返回 true 。 + * + * 示例 2: + * + * 给定二叉树 [1,2,2,3,3,null,null,4,4] + * + * 1 + * / \ + * 2 2 + * / \ + * 3 3 + * / \ + * 4 4 + * 返回 false 。 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/balanced-binary-tree + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _110_isBalanced { + + public static void main(String[] args) { + _110_isBalanced isBalanced = new _110_isBalanced(); + TreeNode treeNode = Util.generateTreeNode(new Integer[]{3, 9, 20, null, null, 15, 7}); + System.out.println(isBalanced.isBalanced(treeNode)); + TreeNode treeNode2 = Util.generateTreeNode(new Integer[]{1,2,2,3,3,null,null,4,4}); + System.out.println(isBalanced.isBalanced(treeNode2)); + } + + /** + * 解题思路: + * 1、递归计算左右子树的高度 + * 2、取左右子树的最大高度+1,即是该根节点的高度 + * 3、由于每个节点都需要满足高度平衡二叉树的条件,所以递归返回一个Pair + * @param root + * @return + */ + public boolean isBalanced(TreeNode root) { + return dfs(root).getKey(); + } + + private Pair dfs(TreeNode root) { + if (root == null) return new Pair<>(true, 0); + Pair left = dfs(root.left); + Pair right = dfs(root.right); + return new Pair<>(left.getKey() && right.getKey() && (Math.abs(left.getValue() - right.getValue()) <= 1), Math.max(left.getValue(), right.getValue()) + 1); + } +} diff --git a/src/pp/arithmetic/leetcode/_1114_Foo.java b/src/pp/arithmetic/leetcode/_1114_Foo.java new file mode 100644 index 0000000..c78916a --- /dev/null +++ b/src/pp/arithmetic/leetcode/_1114_Foo.java @@ -0,0 +1,117 @@ +package pp.arithmetic.leetcode; + +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Created by wangpeng on 2020-03-09. + * 1114. 按序打印 + *

+ * 我们提供了一个类: + *

+ * public class Foo { + *   public void one() { print("one"); } + *   public void two() { print("two"); } + *   public void three() { print("three"); } + * } + * 三个不同的线程将会共用一个 Foo 实例。 + *

+ * 线程 A 将会调用 one() 方法 + * 线程 B 将会调用 two() 方法 + * 线程 C 将会调用 three() 方法 + * 请设计修改程序,以确保 two() 方法在 one() 方法之后被执行,three() 方法在 two() 方法之后被执行。 + *

+ *   + *

+ * 示例 1: + *

+ * 输入: [1,2,3] + * 输出: "onetwothree" + * 解释: + * 有三个线程会被异步启动。 + * 输入 [1,2,3] 表示线程 A 将会调用 one() 方法,线程 B 将会调用 two() 方法,线程 C 将会调用 three() 方法。 + * 正确的输出是 "onetwothree"。 + * 示例 2: + *

+ * 输入: [1,3,2] + * 输出: "onetwothree" + * 解释: + * 输入 [1,3,2] 表示线程 A 将会调用 one() 方法,线程 B 将会调用 three() 方法,线程 C 将会调用 two() 方法。 + * 正确的输出是 "onetwothree"。 + *   + *

+ * 注意: + *

+ * 尽管输入中的数字似乎暗示了顺序,但是我们并不保证线程在操作系统中的调度顺序。 + *

+ * 你看到的输入格式主要是为了确保测试的全面性。 + *

+ * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/print-in-order + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _1114_Foo { + + public static void main(String[] args) { + Foo foo = new Foo(); + Runnable runnable1 = new Runnable() { + @Override + public void run() { + System.out.println("printFirst"); + } + }; + Runnable runnable2 = new Runnable() { + @Override + public void run() { + System.out.println("printSecond"); + } + }; + Runnable runnable3 = new Runnable() { + @Override + public void run() { + System.out.println("printThird"); + } + }; + try { + foo.first(runnable1); + foo.third(runnable3); + foo.second(runnable2); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + } + + //一道题自己没有跑成功,不知道测试用例如何输出的 + static class Foo { + + private AtomicInteger firstJobDone = new AtomicInteger(0); + private AtomicInteger secondJobDone = new AtomicInteger(0); + + public Foo() {} + + public void first(Runnable printFirst) throws InterruptedException { + // printFirst.run() outputs "first". + printFirst.run(); + // mark the first job as done, by increasing its count. + firstJobDone.incrementAndGet(); + } + + public void second(Runnable printSecond) throws InterruptedException { + while (firstJobDone.get() != 1) { + // waiting for the first job to be done. + } + // printSecond.run() outputs "second". + printSecond.run(); + // mark the second as done, by increasing its count. + secondJobDone.incrementAndGet(); + } + + public void third(Runnable printThird) throws InterruptedException { + while (secondJobDone.get() != 1) { + // waiting for the second job to be done. + } + // printThird.run() outputs "third". + printThird.run(); + } + } +} diff --git a/src/pp/arithmetic/leetcode/_1115_FooBar.java b/src/pp/arithmetic/leetcode/_1115_FooBar.java new file mode 100644 index 0000000..b981d43 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_1115_FooBar.java @@ -0,0 +1,111 @@ +package pp.arithmetic.leetcode; + +import java.util.concurrent.Semaphore; + +/** + * Created by wangpeng on 2020-07-08. + * 1115. 交替打印FooBar + *

+ * 我们提供一个类: + *

+ * class FooBar { + * public void foo() { + *     for (int i = 0; i < n; i++) { + *       print("foo"); + *   } + * } + *

+ * public void bar() { + *     for (int i = 0; i < n; i++) { + *       print("bar"); + *     } + * } + * } + * 两个不同的线程将会共用一个 FooBar 实例。其中一个线程将会调用 foo() 方法,另一个线程将会调用 bar() 方法。 + *

+ * 请设计修改程序,以确保 "foobar" 被输出 n 次。 + *

+ *   + *

+ * 示例 1: + *

+ * 输入: n = 1 + * 输出: "foobar" + * 解释: 这里有两个线程被异步启动。其中一个调用 foo() 方法, 另一个调用 bar() 方法,"foobar" 将被输出一次。 + * 示例 2: + *

+ * 输入: n = 2 + * 输出: "foobarfoobar" + * 解释: "foobar" 将被输出两次。 + *

+ * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/print-foobar-alternately + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _1115_FooBar { + + public static void main(String[] args) { + + FooBar fooBar = new FooBar(5); + new Thread() { + @Override + public void run() { + try { + fooBar.foo(new Runnable() { + @Override + public void run() { + System.out.println("foo"); + } + }); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }.start(); + new Thread() { + @Override + public void run() { + try { + fooBar.bar(new Runnable() { + @Override + public void run() { + System.out.println("bar"); + } + }); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }.start(); + + } + + static class FooBar { + private Semaphore fooSe = new Semaphore(0); + private Semaphore barSe = new Semaphore(1); + + private int n; + + public FooBar(int n) { + this.n = n; + } + + public void foo(Runnable printFoo) throws InterruptedException { + + for (int i = 0; i < n; i++) { + barSe.acquire(); + printFoo.run(); + fooSe.release(); + } + } + + public void bar(Runnable printBar) throws InterruptedException { + + for (int i = 0; i < n; i++) { + fooSe.acquire(); + printBar.run(); + barSe.release(); + } + } + } +} diff --git a/src/pp/arithmetic/leetcode/_1116_ZeroEvenOdd.java b/src/pp/arithmetic/leetcode/_1116_ZeroEvenOdd.java new file mode 100644 index 0000000..5aeac21 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_1116_ZeroEvenOdd.java @@ -0,0 +1,125 @@ +package pp.arithmetic.leetcode; + +import java.util.concurrent.Semaphore; +import java.util.function.IntConsumer; + +/** + * Created by wangpeng on 2020-07-09. + * 1116. 打印零与奇偶数 + *

+ * 假设有这么一个类: + *

+ * class ZeroEvenOdd { + *   public ZeroEvenOdd(int n) { ... }  // 构造函数 + * public void zero(printNumber) { ... } // 仅打印出 0 + * public void even(printNumber) { ... } // 仅打印出 偶数 + * public void odd(printNumber) { ... } // 仅打印出 奇数 + * } + * 相同的一个 ZeroEvenOdd 类实例将会传递给三个不同的线程: + *

+ * 线程 A 将调用 zero(),它只输出 0 。 + * 线程 B 将调用 even(),它只输出偶数。 + * 线程 C 将调用 odd(),它只输出奇数。 + * 每个线程都有一个 printNumber 方法来输出一个整数。请修改给出的代码以输出整数序列 010203040506... ,其中序列的长度必须为 2n。 + *

+ *   + *

+ * 示例 1: + *

+ * 输入:n = 2 + * 输出:"0102" + * 说明:三条线程异步执行,其中一个调用 zero(),另一个线程调用 even(),最后一个线程调用odd()。正确的输出为 "0102"。 + * 示例 2: + *

+ * 输入:n = 5 + * 输出:"0102030405" + *

+ * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/print-zero-even-odd + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _1116_ZeroEvenOdd { + + public static void main(String[] args) { + ZeroEvenOdd zeroEvenOdd = new ZeroEvenOdd(5); + IntConsumer printNumber = new IntConsumer() { + @Override + public void accept(int value) { + System.out.println(value); + } + }; + new Thread(){ + @Override + public void run() { + super.run(); + try { + zeroEvenOdd.zero(printNumber); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }.start(); + new Thread(){ + @Override + public void run() { + super.run(); + try { + zeroEvenOdd.even(printNumber); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }.start(); + new Thread(){ + @Override + public void run() { + super.run(); + try { + zeroEvenOdd.odd(printNumber); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }.start(); + } + + static class ZeroEvenOdd { + private int n; + private Semaphore zeroSe = new Semaphore(1); + private Semaphore evenSe = new Semaphore(0); + private Semaphore oddSe = new Semaphore(0); + + public ZeroEvenOdd(int n) { + this.n = n; + } + + // printNumber.accept(x) outputs "x", where x is an integer. + public void zero(IntConsumer printNumber) throws InterruptedException { + for (int i = 0; i < n; i++) { + zeroSe.acquire(); + printNumber.accept(0); + if (i % 2 == 0) { + evenSe.release(); + } else { + oddSe.release(); + } + } + } + + public void even(IntConsumer printNumber) throws InterruptedException { + for (int i = 1; i <= n; i+=2) { + evenSe.acquire(); + printNumber.accept(i); + zeroSe.release(); + } + } + + public void odd(IntConsumer printNumber) throws InterruptedException { + for (int i = 2; i <= n; i+=2) { + oddSe.acquire(); + printNumber.accept(i); + zeroSe.release(); + } + } + } +} diff --git a/src/pp/arithmetic/leetcode/_1117_H2O.java b/src/pp/arithmetic/leetcode/_1117_H2O.java new file mode 100644 index 0000000..79a195e --- /dev/null +++ b/src/pp/arithmetic/leetcode/_1117_H2O.java @@ -0,0 +1,197 @@ +package pp.arithmetic.leetcode; + +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.Semaphore; + +/** + * Created by wangpeng on 2020-07-15. + * 1117. H2O 生成 + *

+ * 现在有两种线程,氧 oxygen 和氢 hydrogen,你的目标是组织这两种线程来产生水分子。 + *

+ * 存在一个屏障(barrier)使得每个线程必须等候直到一个完整水分子能够被产生出来。 + *

+ * 氢和氧线程会被分别给予 releaseHydrogen 和 releaseOxygen 方法来允许它们突破屏障。 + *

+ * 这些线程应该三三成组突破屏障并能立即组合产生一个水分子。 + *

+ * 你必须保证产生一个水分子所需线程的结合必须发生在下一个水分子产生之前。 + *

+ * 换句话说: + *

+ * 如果一个氧线程到达屏障时没有氢线程到达,它必须等候直到两个氢线程到达。 + * 如果一个氢线程到达屏障时没有其它线程到达,它必须等候直到一个氧线程和另一个氢线程到达。 + * 书写满足这些限制条件的氢、氧线程同步代码。 + *

+ *   + *

+ * 示例 1: + *

+ * 输入: "HOH" + * 输出: "HHO" + * 解释: "HOH" 和 "OHH" 依然都是有效解。 + * 示例 2: + *

+ * 输入: "OOHHHH" + * 输出: "HHOHHO" + * 解释: "HOHHHO", "OHHHHO", "HHOHOH", "HOHHOH", "OHHHOH", "HHOOHH", "HOHOHH" 和 "OHHOHH" 依然都是有效解。 + *   + *

+ * 提示: + *

+ * 输入字符串的总长将会是 3n, 1 ≤ n ≤ 50; + * 输入字符串中的 “H” 总数将会是 2n 。 + * 输入字符串中的 “O” 总数将会是 n 。 + *

+ * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/building-h2o + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _1117_H2O { + + + public static void main(String[] args) { + + int n = 6; + H2O h2O = new H2O(); + for (int i = 0; i < n * 2; i++) { + //H + new Thread() { + @Override + public void run() { + super.run(); + try { + h2O.hydrogen(new Runnable() { + @Override + public void run() { + System.out.println("H"); + } + }); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }.start(); + } + for (int i = 0; i < n; i++) { + //O + new Thread() { + @Override + public void run() { + super.run(); + try { + h2O.oxygen(new Runnable() { + @Override + public void run() { + System.out.println("O"); + } + }); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }.start(); + } + } + + //使用系统类进行优化 + class H2O2 { + + private Semaphore hs; + private Semaphore os; + private CyclicBarrier totalBarrier; + + public H2O2() { + hs = new Semaphore(2); + os = new Semaphore(1); + //await用于标识等待所有的线程都达到barrier才继续执行 + totalBarrier = new CyclicBarrier(3); + } + + public void hydrogen(Runnable releaseHydrogen) throws InterruptedException { + hs.acquire(); + // releaseHydrogen.run() outputs "H". Do not change or remove this line. + releaseHydrogen.run(); + try { + totalBarrier.await(); + } catch (BrokenBarrierException e) { + e.printStackTrace(); + } + hs.release(); + } + + public void oxygen(Runnable releaseOxygen) throws InterruptedException { + os.acquire(); + // releaseOxygen.run() outputs "O". Do not change or remove this line. + releaseOxygen.run(); + try { + totalBarrier.await(); + } catch (BrokenBarrierException e) { + e.printStackTrace(); + } + os.release(); + } + } + + + static class H2O { + + private final Object lock = new Object(); + private int hc = 2; + private int oc = 1; + + public H2O() { + + } + + public void hydrogen(Runnable releaseHydrogen) throws InterruptedException { + + boolean flag = false; + synchronized (lock) { + while (hc == 0) { + lock.wait(); + synchronized (lock) { + if (hc > 0) { + hc--; + flag = true; + break; + } + } + } + if (!flag) hc--; + // releaseHydrogen.run() outputs "H". Do not change or remove this line. + releaseHydrogen.run(); + reset(); + } + } + + public void oxygen(Runnable releaseOxygen) throws InterruptedException { + boolean flag = false; + synchronized (lock) { + while (oc == 0) { + lock.wait(); + synchronized (lock) { + if (oc > 0) { + oc--; + flag = true; + break; + } + } + } + if (!flag) oc--; + // releaseOxygen.run() outputs "O". Do not change or remove this line. + releaseOxygen.run(); + reset(); + } + } + + private void reset() { + if (hc == 0 && oc == 0) { + hc = 2; + oc = 1; + lock.notifyAll(); + } + } + } +} diff --git a/src/pp/arithmetic/leetcode/_111_minDepth.java b/src/pp/arithmetic/leetcode/_111_minDepth.java new file mode 100644 index 0000000..b294a1e --- /dev/null +++ b/src/pp/arithmetic/leetcode/_111_minDepth.java @@ -0,0 +1,55 @@ +package pp.arithmetic.leetcode; + +import pp.arithmetic.Util; +import pp.arithmetic.model.TreeNode; + +/** + * Created by wangpeng on 2019-12-12. + * 111. 二叉树的最小深度 + * + * 给定一个二叉树,找出其最小深度。 + * + * 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 + * + * 说明: 叶子节点是指没有子节点的节点。 + * + * 示例: + * + * 给定二叉树 [3,9,20,null,null,15,7], + * + * 3 + * / \ + * 9 20 + * / \ + * 15 7 + * 返回它的最小深度  2. + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _111_minDepth { + + public static void main(String[] args) { + _111_minDepth minDepth = new _111_minDepth(); + System.out.println(minDepth.minDepth(Util.generateTreeNode(new Integer[]{3, 9, 20, null, null, 15, 7}))); + } + + /** + * 解题思路:DFS求解 + * 1、求左子树的最小深度 + * 2、求右子树的最小深度 + * 3、求根节点的最小深度 = Math.min(left,right)+1 + * + * 需要注意一点:如左/右子树为空,得取有值得叶节点长度 + * + * @param root + * @return + */ + public int minDepth(TreeNode root) { + if (root == null) return 0; + int left = minDepth(root.left); + int right = minDepth(root.right); + return (left == 0 || right == 0) ? left + right + 1 : Math.min(left, right) + 1; + } +} diff --git a/src/pp/arithmetic/leetcode/_112_hasPathSum.java b/src/pp/arithmetic/leetcode/_112_hasPathSum.java new file mode 100644 index 0000000..cc37d2e --- /dev/null +++ b/src/pp/arithmetic/leetcode/_112_hasPathSum.java @@ -0,0 +1,67 @@ +package pp.arithmetic.leetcode; + +import pp.arithmetic.Util; +import pp.arithmetic.model.TreeNode; + +/** + * Created by wangpeng on 2019-12-12. + * 112. 路径总和 + * + * 给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。 + * + * 说明: 叶子节点是指没有子节点的节点。 + * + * 示例:  + * 给定如下二叉树,以及目标和 sum = 22, + * + * 5 + * / \ + * 4 8 + * / / \ + * 11 13 4 + * / \ \ + * 7 2 1 + * 返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/path-sum + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _112_hasPathSum { + + public static void main(String[] args) { + _112_hasPathSum hasPathSum = new _112_hasPathSum(); + TreeNode treeNode = Util.generateTreeNode(new Integer[]{5, 4, 7, 11, null, 13, 4, 7, 2, null, null, null, 1}); + System.out.println(hasPathSum.hasPathSum(treeNode,22)); + System.out.println(hasPathSum.hasPathSum(Util.generateTreeNode(new Integer[]{1,2}),1)); + } + + /** + * 解题思路: + * 1、sum减去当前根节点的val,将新的sum传递给左右子树 + * 2、左右子树重复步骤1 + * 3、如最终的节点==null并且sum==0则找到目标路径 + * + * 注意:叶节点的定义 + * + * @param root + * @param sum + * @return + */ + public boolean hasPathSum(TreeNode root, int sum) { + if (root == null) return false; + return dfs(root, sum); + } + + private boolean dfs(TreeNode root, int sum) { + if (root == null) return sum == 0; + int newSum = sum - root.val; + if (root.left == null && root.right == null) return newSum == 0; + boolean left = dfs(root.left, newSum); + boolean right = dfs(root.right, newSum); + if (root.left != null && root.right != null) return left || right; + if (root.left != null) return left; + if (root.right != null) return right; + return false; + } +} diff --git a/src/pp/arithmetic/leetcode/_115_numDistinct.java b/src/pp/arithmetic/leetcode/_115_numDistinct.java new file mode 100644 index 0000000..1610c0b --- /dev/null +++ b/src/pp/arithmetic/leetcode/_115_numDistinct.java @@ -0,0 +1,142 @@ +package pp.arithmetic.leetcode; + +import pp.arithmetic.Util; + +/** + * Created by wangpeng on 2019-12-13. + * 115. 不同的子序列 + * + * 给定一个字符串 S 和一个字符串 T,计算在 S 的子序列中 T 出现的个数。 + * + * 一个字符串的一个子序列是指,通过删除一些(也可以不删除)字符且不干扰剩余字符相对位置所组成的新字符串。(例如,"ACE" 是 "ABCDE" 的一个子序列,而 "AEC" 不是) + * + * 示例 1: + * + * 输入: S = "rabbbit", T = "rabbit" + * 输出: 3 + * 解释: + * + * 如下图所示, 有 3 种可以从 S 中得到 "rabbit" 的方案。 + * (上箭头符号 ^ 表示选取的字母) + * + * rabbbit + * ^^^^ ^^ + * rabbbit + * ^^ ^^^^ + * rabbbit + * ^^^ ^^^ + * 示例 2: + * + * 输入: S = "babgbag", T = "bag" + * 输出: 5 + * 解释: + * + * 如下图所示, 有 5 种可以从 S 中得到 "bag" 的方案。 + * (上箭头符号 ^ 表示选取的字母) + * + * babgbag + * ^^ ^ + * babgbag + * ^^ ^ + * babgbag + * ^ ^^ + * babgbag + * ^ ^^ + * babgbag + * ^^^ + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/distinct-subsequences + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _115_numDistinct { + + public static void main(String[] args) { + _115_numDistinct numDistinct = new _115_numDistinct(); + System.out.println(numDistinct.numDistinct("aaa", "aa")); + System.out.println(numDistinct.numDistinct("rabbbit", "rabbit")); + System.out.println(numDistinct.numDistinct("babgbag", "bag")); + System.out.println(numDistinct.numDistinct("adbdadeecadeadeccaeaabdabdbcdabddddabcaaadbabaaedeeddeaeebcdeabcaaaeeaeeabcddcebddebeebedaecccbdcbcedbdaeaedcdebeecdaaedaacadbdccabddaddacdddc", "bcddceeeebecbc")); + Util.printDivideLine(); + System.out.println(numDistinct.numDistinct2("babgbag", "bag")); + System.out.println(numDistinct.numDistinct2("aaa", "aa")); + System.out.println(numDistinct.numDistinct2("rabbbit", "rabbit")); + System.out.println(numDistinct.numDistinct2("adbdadeecadeadeccaeaabdabdbcdabddddabcaaadbabaaedeeddeaeebcdeabcaaaeeaeeabcddcebddebeebedaecccbdcbcedbdaeaedcdebeecdaaedaacadbdccabddaddacdddc", "bcddceeeebecbc")); + } + + /** + * 解题思路: + * 通过模拟题意中的过程,感知有点回溯的感觉: + * 1、优先匹配前面的 + * 2、匹配上了之后,再匹配后面的 + * 3、直到匹配到最后一个,向后搜索匹配的,直到末尾 + * 4、最后一位匹配到末尾之后,倒数第二位向后搜索匹配 + * 5、如此循环,直至第一位也匹配到末尾结束 + * + * 可解题,遇到复杂的提交超时: + * 比如这跟case: + * "adbdadeecadeadeccaeaabdabdbcdabddddabcaaadbabaaedeeddeaeebcdeabcaaaeeaeeabcddcebddebeebedaecccbdcbcedbdaeaedcdebeecdaaedaacadbdccabddaddacdddc" + * "bcddceeeebecbc" + * 本地跑出结果:700531452 + * + * 优化思考:是不是可以考虑将遍历过程中的一些结果保存起来,而不是每次凑重新计算==>动态规划{@link _115_numDistinct#numDistinct2(String, String)} + * + * @param s + * @param t + * @return + */ + public int numDistinct(String s, String t) { + if (s.length() < t.length()) return 0; + int sum = 0; + int ti = 0; + int si = 0; + while (si < s.length() && ti < t.length()) { + if (s.charAt(si) == t.charAt(ti)) { + if (si + 1 < s.length() && ti + 1 < t.length()) { + sum += numDistinct(s.substring(si + 1), t.substring(ti + 1)); + } else { + if (ti == t.length() - 1) { + sum += 1; + } + } + } + si++; + } + + return sum; + } + + /** + * 优化求解:找递进规律(s:babgbag,t:bag) + * T/S "" b a b g b a g + * "" 1 1 1 1 1 1 1 1 + * b 0 1 1 2 2 3 3 3 + * a 0 0 1 1 1 1 4 4 + * g 0 0 0 0 1 1 1 5 + * + * dp[t.length() + 1][s.length() + 1] : dp[i][j]代表t[0-i]在s[0-j]中的出现的次数 + * 如果某一位t[i]==s[j],则此时的次数=dp[i-1][j-1]+dp[i][j-1] + * 如果某一位t[i]!=s[j],则此时的次数=dp[i][j-1] + * + * 执行用时 :7 ms, 在所有 java 提交中击败了79.83%的用户 + * 内存消耗 :35.8 MB, 在所有 java 提交中击败了85.40%的用户 + * + * @param s + * @param t + * @return + */ + public int numDistinct2(String s, String t) { + int[][] dp = new int[t.length() + 1][s.length() + 1]; + for (int j = 0; j < s.length() + 1; j++) dp[0][j] = 1; + for (int i = 1; i < t.length() + 1; i++) { + for (int j = 1; j < s.length() + 1; j++) { + if (t.charAt(i - 1) == s.charAt(j - 1)) { + dp[i][j] = dp[i - 1][j - 1] + dp[i][j - 1]; + } else { + dp[i][j] = dp[i][j - 1]; + } + } + } + return dp[t.length()][s.length()]; + } +} diff --git a/src/pp/arithmetic/leetcode/_116_connect.java b/src/pp/arithmetic/leetcode/_116_connect.java new file mode 100644 index 0000000..27b27dd --- /dev/null +++ b/src/pp/arithmetic/leetcode/_116_connect.java @@ -0,0 +1,81 @@ +package pp.arithmetic.leetcode; + +import pp.arithmetic.model.Node; + +/** + * Created by wangpeng on 2019-12-14. + * 116. 填充每个节点的下一个右侧节点指针 + * + * 给定一个完美二叉树,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下: + * + * struct Node { + * int val; + * Node *left; + * Node *right; + * Node *next; + * } + * 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。 + * + * 初始状态下,所有 next 指针都被设置为 NULL。 + * + *   + * + * 示例: + * + * https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/02/15/116_sample.png + * + * + * 输入:{"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,"next":null,"right":null,"val":4},"next":null,"right":{"$id":"4","left":null,"next":null,"right":null,"val":5},"val":2},"next":null,"right":{"$id":"5","left":{"$id":"6","left":null,"next":null,"right":null,"val":6},"next":null,"right":{"$id":"7","left":null,"next":null,"right":null,"val":7},"val":3},"val":1} + * + * 输出:{"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,"next":{"$id":"4","left":null,"next":{"$id":"5","left":null,"next":{"$id":"6","left":null,"next":null,"right":null,"val":7},"right":null,"val":6},"right":null,"val":5},"right":null,"val":4},"next":{"$id":"7","left":{"$ref":"5"},"next":null,"right":{"$ref":"6"},"val":3},"right":{"$ref":"4"},"val":2},"next":null,"right":{"$ref":"7"},"val":1} + * + * 解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。 + *   + * + * 提示: + * + * 你只能使用常量级额外空间。 + * 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _116_connect { + + public static void main(String[] args) { + _116_connect connect = new _116_connect(); + Node node = new Node(1); + node.left = new Node(2); + node.right = new Node(3); + node.left.left = new Node(4); + node.left.right = new Node(5); + node.right.left = new Node(6); + node.right.right = new Node(7); + connect.connect(node); + System.out.println(); + } + + /** + * 解题思路: + * 总结题意:BFS遍历的时候将每一层的节点用next指针关联起来,难点是只能使用常量级空间 + * 1、将左子树的最后侧,右子树的最左侧连接,同级向下一层层循环 + * 2、同理作用于根节点的左右子树 + * + * @param root + * @return + */ + public Node connect(Node root) { + if (root == null) return null; + Node left = root.left; + Node right = root.right; + while (left != null) { + left.next = right; + left = left.right; + right = right.left; + } + connect(root.left); + connect(root.right); + return root; + } +} diff --git a/src/pp/arithmetic/leetcode/_117_connect.java b/src/pp/arithmetic/leetcode/_117_connect.java new file mode 100644 index 0000000..8db4604 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_117_connect.java @@ -0,0 +1,97 @@ +package pp.arithmetic.leetcode; + +import pp.arithmetic.model.Node; + +/** + * Created by wangpeng on 2019-12-16. + * 117. 填充每个节点的下一个右侧节点指针 II + * + * 给定一个二叉树 + * + * struct Node { + * int val; + * Node *left; + * Node *right; + * Node *next; + * } + * 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。 + * + * 初始状态下,所有 next 指针都被设置为 NULL。 + * + *   + * + * 进阶: + * + * 你只能使用常量级额外空间。 + * 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。 + *   + * + * 示例: + * + * https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/02/15/117_sample.png + * + * 输入:root = [1,2,3,4,5,null,7] + * 输出:[1,#,2,3,#,4,5,7,#] + * 解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。 + *   + * + * 提示: + * + * 树中的节点数小于 6000 + * -100 <= node.val <= 100 + *   + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _117_connect { + + public static void main(String[] args) { + //[1,2,3,4,5,null,6,7,null,null,null,null,8] + //[1,#,2,3,#,4,5,6,#,7,#] + //[1,#,2,3,#,4,5,6,#,7,8,#] + _117_connect connect = new _117_connect(); + Node node = new Node(1); + node.left = new Node(2); + node.right = new Node(3); + node.left.left = new Node(4); + node.left.right = new Node(5); + node.right.right = new Node(6); + node.left.left.left = new Node(7); + node.right.right.right = new Node(8); + connect.connect(node); + System.out.println(); + } + + /** + * 解题思路:题目和{@link _116_connect}类似,唯一区别是此题不是完美二叉树,可能存在子树为空,所以不能使用116的解法, + * 得求解每一层需要连接的左右子树 + * + * @param root + * @return + */ + public Node connect(Node root) { + Node cur = root; + while (cur != null) { + Node dummy = new Node(); + Node tail = dummy; + //遍历 cur 的当前层 + while (cur != null) { + if (cur.left != null) { + tail.next = cur.left; + tail = tail.next; + } + if (cur.right != null) { + tail.next = cur.right; + tail = tail.next; + } + cur = cur.next; + } + //更新 cur 到下一层 + cur = dummy.next; + } + return root; + } + +} diff --git a/src/pp/arithmetic/leetcode/_118_generate.java b/src/pp/arithmetic/leetcode/_118_generate.java new file mode 100644 index 0000000..02952cb --- /dev/null +++ b/src/pp/arithmetic/leetcode/_118_generate.java @@ -0,0 +1,74 @@ +package pp.arithmetic.leetcode; + +import pp.arithmetic.Util; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by wangpeng on 2019-12-18. + * 118. 杨辉三角 + * + * + * 给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。 + * + * https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif + * + * 在杨辉三角中,每个数是它左上方和右上方的数的和。 + * + * 示例: + * + * 输入: 5 + * 输出: + * [ + * [1], + * [1,1], + * [1,2,1], + * [1,3,3,1], + * [1,4,6,4,1] + * ] + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/pascals-triangle + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _118_generate { + + + public static void main(String[] args) { + _118_generate generate = new _118_generate(); + List> list = generate.generate(5); + for (int i = 0; i < list.size(); i++) { + Util.printList(list.get(i)); + } + } + + /** + * 解题思路: + * 0、用一个list数组保存上一行的遍历结果 + * 1、当下一行是头和尾,直接赋值1 + * 2、当下一行在中间位置j,结果=preItem.get(j - 1) + preItem.get(j) + * + * 执行用时 :1 ms, 在所有 java 提交中击败了98.18%的用户 + * 内存消耗 :34.5 MB, 在所有 java 提交中击败了25.70%的用户 + * @param numRows + * @return + */ + public List> generate(int numRows) { + List> retList = new ArrayList<>(); + List preItem = null; + for (int i = 0; i < numRows; i++) { + List item = new ArrayList<>(); + for (int j = 0; j <= i; j++) { + if (j == 0 || j == i) { + item.add(1); + } else { + item.add(preItem.get(j - 1) + preItem.get(j)); + } + } + preItem = item; + retList.add(item); + } + return retList; + } +} diff --git a/src/pp/arithmetic/leetcode/_1195_FizzBuzz.java b/src/pp/arithmetic/leetcode/_1195_FizzBuzz.java new file mode 100644 index 0000000..1c000d7 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_1195_FizzBuzz.java @@ -0,0 +1,187 @@ +package pp.arithmetic.leetcode; + +import java.util.concurrent.Semaphore; +import java.util.function.IntConsumer; + +/** + * Created by wangpeng on 2020-07-16. + * 1195. 交替打印字符串 + *

+ * 编写一个可以从 1 到 n 输出代表这个数字的字符串的程序,但是: + *

+ * 如果这个数字可以被 3 整除,输出 "fizz"。 + * 如果这个数字可以被 5 整除,输出 "buzz"。 + * 如果这个数字可以同时被 3 和 5 整除,输出 "fizzbuzz"。 + * 例如,当 n = 15,输出: 1, 2, fizz, 4, buzz, fizz, 7, 8, fizz, buzz, 11, fizz, 13, 14, fizzbuzz。 + *

+ * 假设有这么一个类: + *

+ * class FizzBuzz { + *   public FizzBuzz(int n) { ... }  // constructor + * public void fizz(printFizz) { ... } // only output "fizz" + * public void buzz(printBuzz) { ... } // only output "buzz" + * public void fizzbuzz(printFizzBuzz) { ... } // only output "fizzbuzz" + * public void number(printNumber) { ... } // only output the numbers + * } + * 请你实现一个有四个线程的多线程版  FizzBuzz, 同一个 FizzBuzz 实例会被如下四个线程使用: + *

+ * 线程A将调用 fizz() 来判断是否能被 3 整除,如果可以,则输出 fizz。 + * 线程B将调用 buzz() 来判断是否能被 5 整除,如果可以,则输出 buzz。 + * 线程C将调用 fizzbuzz() 来判断是否同时能被 3 和 5 整除,如果可以,则输出 fizzbuzz。 + * 线程D将调用 number() 来实现输出既不能被 3 整除也不能被 5 整除的数字。 + *

+ * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/fizz-buzz-multithreaded + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _1195_FizzBuzz { + + public static void main(String[] args) { + FizzBuzz fizzBuzz = new FizzBuzz(16); + new Thread() { + @Override + public void run() { + super.run(); + try { + fizzBuzz.fizz(new Runnable() { + @Override + public void run() { + System.out.println("fizz"); + } + }); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }.start(); + new Thread() { + @Override + public void run() { + super.run(); + try { + fizzBuzz.buzz(new Runnable() { + @Override + public void run() { + System.out.println("buzz"); + } + }); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }.start(); + new Thread() { + @Override + public void run() { + super.run(); + try { + fizzBuzz.fizzbuzz(new Runnable() { + @Override + public void run() { + System.out.println("fizzbuzz"); + } + }); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }.start(); + new Thread() { + @Override + public void run() { + super.run(); + try { + fizzBuzz.number(new IntConsumer() { + @Override + public void accept(int value) { + System.out.println(value); + } + }); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }.start(); + } + + /** + * 解题思路:对于多线程的问题,无非是加锁、等待、解锁、通知, + */ + static class FizzBuzz { + private int n; + private int pn = 1; + private Semaphore fs = new Semaphore(0); + private Semaphore bs = new Semaphore(0); + private Semaphore fbs = new Semaphore(0); + private Semaphore ns = new Semaphore(1); + + public FizzBuzz(int n) { + this.n = n; + } + + // printFizz.run() outputs "fizz". + public void fizz(Runnable printFizz) throws InterruptedException { + while (pn <= n) { + fs.acquire(); + if (pn > n) break; + printFizz.run(); + pn++; + notifyPrint(); + } + } + + // printBuzz.run() outputs "buzz". + public void buzz(Runnable printBuzz) throws InterruptedException { + while (pn <= n) { + bs.acquire(); + if (pn > n) break; + printBuzz.run(); + pn++; + notifyPrint(); + } + } + + // printFizzBuzz.run() outputs "fizzbuzz". + public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException { + while (pn <= n) { + fbs.acquire(); + if (pn > n) break; + printFizzBuzz.run(); + pn++; + notifyPrint(); + } + } + + // printNumber.accept(x) outputs "x", where x is an integer. + public void number(IntConsumer printNumber) throws InterruptedException { + while (pn <= n) { + ns.acquire(); + if (pn > n) break; + printNumber.accept(pn); + pn++; + notifyPrint(); + } + } + + private void notifyPrint() { + if (pn > n) { + fs.release(); + bs.release(); + fbs.release(); + ns.release(); + return; + } + boolean m3 = pn % 3 == 0; + boolean m5 = pn % 5 == 0; + if (m3 && m5) { + fbs.release(); + } else if (m3) { + fs.release(); + } else if (m5) { + bs.release(); + } else { + ns.release(); + } + } + } +} diff --git a/src/pp/arithmetic/leetcode/_119_getRow.java b/src/pp/arithmetic/leetcode/_119_getRow.java new file mode 100644 index 0000000..4ab63d3 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_119_getRow.java @@ -0,0 +1,61 @@ +package pp.arithmetic.leetcode; + +import pp.arithmetic.Util; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by wangpeng on 2019-12-18. + * 119. 杨辉三角 II + * + * 给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。 + * + * https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif + * + * 在杨辉三角中,每个数是它左上方和右上方的数的和。 + * + * 示例: + * + * 输入: 3 + * 输出: [1,3,3,1] + * 进阶: + * + * 你可以优化你的算法到 O(k) 空间复杂度吗? + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/pascals-triangle-ii + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _119_getRow { + + public static void main(String[] args) { + _119_getRow getRow = new _119_getRow(); + Util.printList(getRow.getRow(6)); + } + + /** + * 解题思路: + * 最简单的就是像 {@link _118_generate} 中解题方式,求出第row行的结果,可是期望 O(k) 空间复杂度,这是难点 + * 考虑能不能通过规律找出直接计算第row行的结果? + * 通过杨辉三角规律可知,第i行第j个得数字结果是(i,j)的组合数 + * + * 执行用时 :1 ms, 在所有 java 提交中击败了93.68%的用户 + * 内存消耗 :33.6 MB, 在所有 java 提交中击败了23.63%的用户 + * + * @param rowIndex + * @return + */ + public List getRow(int rowIndex) { + List retList = new ArrayList<>(); + int N = rowIndex; + long pre = 1; + retList.add(1); + for (int k = 1; k <= N; k++) { + long cur = pre * (N - k + 1) / k; + retList.add((int) cur); + pre = cur; + } + return retList; + } +} diff --git a/src/pp/arithmetic/leetcode/_1226_DiningPhilosophers.java b/src/pp/arithmetic/leetcode/_1226_DiningPhilosophers.java new file mode 100644 index 0000000..291cf68 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_1226_DiningPhilosophers.java @@ -0,0 +1,155 @@ +package pp.arithmetic.leetcode; + +import java.util.concurrent.Semaphore; + +/** + * Created by wangpeng on 2020-07-17. + * 1226. 哲学家进餐 + * + * 5 个沉默寡言的哲学家围坐在圆桌前,每人面前一盘意面。叉子放在哲学家之间的桌面上。(5 个哲学家,5 根叉子) + * + * 所有的哲学家都只会在思考和进餐两种行为间交替。哲学家只有同时拿到左边和右边的叉子才能吃到面,而同一根叉子在同一时间只能被一个哲学家使用。每个哲学家吃完面后都需要把叉子放回桌面以供其他哲学家吃面。只要条件允许,哲学家可以拿起左边或者右边的叉子,但在没有同时拿到左右叉子时不能进食。 + * + * 假设面的数量没有限制,哲学家也能随便吃,不需要考虑吃不吃得下。 + * + * 设计一个进餐规则(并行算法)使得每个哲学家都不会挨饿;也就是说,在没有人知道别人什么时候想吃东西或思考的情况下,每个哲学家都可以在吃饭和思考之间一直交替下去。 + * + * + * 问题描述和图片来自维基百科 wikipedia.org + * 图片地址:https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/10/23/an_illustration_of_the_dining_philosophers_problem.png + * + * + * 哲学家从 0 到 4 按 顺时针 编号。请实现函数 void wantsToEat(philosopher, pickLeftFork, pickRightFork, eat, putLeftFork, putRightFork): + * + * philosopher 哲学家的编号。 + * pickLeftFork 和 pickRightFork 表示拿起左边或右边的叉子。 + * eat 表示吃面。 + * putLeftFork 和 putRightFork 表示放下左边或右边的叉子。 + * 由于哲学家不是在吃面就是在想着啥时候吃面,所以思考这个方法没有对应的回调。 + * 给你 5 个线程,每个都代表一个哲学家,请你使用类的同一个对象来模拟这个过程。在最后一次调用结束之前,可能会为同一个哲学家多次调用该函数。 + * + *   + * + * 示例: + * + * 输入:n = 1 + * 输出:[[4,2,1],[4,1,1],[0,1,1],[2,2,1],[2,1,1],[2,0,3],[2,1,2],[2,2,2],[4,0,3],[4,1,2],[0,2,1],[4,2,2],[3,2,1],[3,1,1],[0,0,3],[0,1,2],[0,2,2],[1,2,1],[1,1,1],[3,0,3],[3,1,2],[3,2,2],[1,0,3],[1,1,2],[1,2,2]] + * 解释: + * n 表示每个哲学家需要进餐的次数。 + * 输出数组描述了叉子的控制和进餐的调用,它的格式如下: + * output[i] = [a, b, c] (3个整数) + * - a 哲学家编号。 + * - b 指定叉子:{1 : 左边, 2 : 右边}. + * - c 指定行为:{1 : 拿起, 2 : 放下, 3 : 吃面}。 + * 如 [4,2,1] 表示 4 号哲学家拿起了右边的叉子。 + *   + * + * 提示: + * + * 1 <= n <= 60 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/the-dining-philosophers + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _1226_DiningPhilosophers { + + public static void main(String[] args) { + DiningPhilosophers diningPhilosophers = new DiningPhilosophers(); + for (int i = 0; i < 5; i++) { + int finalI = i; + new Thread(){ + @Override + public void run() { + super.run(); + try { + diningPhilosophers.wantsToEat(finalI, new Runnable() { + @Override + public void run() { + System.out.println("["+finalI+",1,1]"); + } + }, new Runnable() { + @Override + public void run() { + System.out.println("["+finalI+",2,1]"); + } + }, new Runnable() { + @Override + public void run() { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("["+finalI+",0,3]"); + } + }, new Runnable() { + @Override + public void run() { + System.out.println("["+finalI+",1,2]"); + } + }, new Runnable() { + @Override + public void run() { + System.out.println("["+finalI+",2,2]"); + } + }); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }.start(); + } + } + + /** + * 解题思路: + * 资源:5个叉子(5个信号量),同时拿到两个叉子(1个互斥信号量,防止死锁),此题解并不是最优解,最优解应该能满足多个同时进餐 + */ + static class DiningPhilosophers { + //一个互斥信号量用于临界资源的互斥访问 + private Semaphore mutex; + //5个同步信号量用于哲学家之间的同步访问 + private Semaphore[] sema; + public DiningPhilosophers() { + mutex = new Semaphore(1); + sema = new Semaphore[] { + new Semaphore(1), + new Semaphore(1), + new Semaphore(1), + new Semaphore(1), + new Semaphore(1) + }; + } + + // call the run() method of any runnable to execute its code + public void wantsToEat(int philosopher, + Runnable pickLeftFork, + Runnable pickRightFork, + Runnable eat, + Runnable putLeftFork, + Runnable putRightFork) throws InterruptedException { + //一个哲学家如果要拿起叉子就同时拿两个,因此这里是一个原子操作,需要用mutex信号量包起来,表示互斥 + mutex.acquire(); + //尝试获取左手边的叉子 + sema[philosopher].acquire(); + //尝试获取右手边的叉子 + sema[(philosopher+1) % 5].acquire(); + + pickLeftFork.run(); + pickRightFork.run(); + //我认为这句话应该放在这里。 + // mutex.release(); + + //拿到叉子开始吃饭 + eat.run(); + + //吃完饭放下叉子 + putLeftFork.run(); + sema[philosopher].release(); + putRightFork.run(); + sema[(philosopher+1) % 5].release(); + mutex.release(); + } + } +} diff --git a/src/pp/arithmetic/leetcode/_129_sumNumbers.java b/src/pp/arithmetic/leetcode/_129_sumNumbers.java new file mode 100644 index 0000000..d9a28e5 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_129_sumNumbers.java @@ -0,0 +1,84 @@ +package pp.arithmetic.leetcode; + +import pp.arithmetic.Util; +import pp.arithmetic.model.TreeNode; + +/** + * Created by wangpeng on 2019-12-21. + * 129. 求根到叶子节点数字之和 + * + * 给定一个二叉树,它的每个结点都存放一个 0-9 的数字,每条从根到叶子节点的路径都代表一个数字。 + * + * 例如,从根到叶子节点路径 1->2->3 代表数字 123。 + * + * 计算从根到叶子节点生成的所有数字之和。 + * + * 说明: 叶子节点是指没有子节点的节点。 + * + * 示例 1: + * + * 输入: [1,2,3] + * 1 + * / \ + * 2 3 + * 输出: 25 + * 解释: + * 从根到叶子节点路径 1->2 代表数字 12. + * 从根到叶子节点路径 1->3 代表数字 13. + * 因此,数字总和 = 12 + 13 = 25. + * 示例 2: + * + * 输入: [4,9,0,5,1] + * 4 + * / \ + * 9 0 + *  / \ + * 5 1 + * 输出: 1026 + * 解释: + * 从根到叶子节点路径 4->9->5 代表数字 495. + * 从根到叶子节点路径 4->9->1 代表数字 491. + * 从根到叶子节点路径 4->0 代表数字 40. + * 因此,数字总和 = 495 + 491 + 40 = 1026. + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/sum-root-to-leaf-numbers + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _129_sumNumbers { + + public static void main(String[] args) { + _129_sumNumbers sumNumbers = new _129_sumNumbers(); + TreeNode treeNode = Util.generateTreeNode(new Integer[]{4, 9, 0, 5, 1}); + System.out.println(sumNumbers.sumNumbers(treeNode)); + } + + private int sum = 0; + + /** + * 解题思路: + * DFS遍历将之前的拼接节点代入,当到达叶节点后累加结果 + * + * @param root + * @return + */ + public int sumNumbers(TreeNode root) { + if (root == null) return 0; + dfs("",root); + return sum; + } + + private void dfs(String preVal, TreeNode root) { + if (root.left == null && root.right == null) { + sum += Integer.parseInt(preVal + root.val); + return; + } + if (root.left != null) { + dfs(preVal + root.val, root.left); + } + if (root.right != null) { + dfs(preVal + root.val, root.right); + } + } + +} diff --git a/src/pp/arithmetic/leetcode/_130_solve.java b/src/pp/arithmetic/leetcode/_130_solve.java new file mode 100644 index 0000000..cbb37cd --- /dev/null +++ b/src/pp/arithmetic/leetcode/_130_solve.java @@ -0,0 +1,88 @@ +package pp.arithmetic.leetcode; + +/** + * Created by wangpeng on 2019-12-23. + * 130. 被围绕的区域 + * + * 给定一个二维的矩阵,包含 'X' 和 'O'(字母 O)。 + * + * 找到所有被 'X' 围绕的区域,并将这些区域里所有的 'O' 用 'X' 填充。 + * + * 示例: + * + * X X X X + * X O O X + * X X O X + * X O X X + * 运行你的函数后,矩阵变为: + * + * X X X X + * X X X X + * X X X X + * X O X X + * 解释: + * + * 被围绕的区间不会存在于边界上,换句话说,任何边界上的 'O' 都不会被填充为 'X'。 任何不在边界上,或不与边界上的 'O' 相连的 'O' 最终都会被填充为 'X'。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/surrounded-regions + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _130_solve { + + public static void main(String[] args) { + _130_solve solve = new _130_solve(); + char[][] chars = { + {'X', 'X', 'X', 'X'}, + {'X', 'O', 'X', 'X'}, + {'X', 'X', 'O', 'X'}, + {'X', 'O', 'X', 'X'} + }; + solve.solve(chars); + } + + /** + * 解题思路: + * 难点:如何确定一个O是否被X全部给围住 + * char[][] board构建的其实是一张图,可以考虑使用图的DFS遍历 + * + * @param board + */ + public void solve(char[][] board) { + if (board == null || board.length == 0) return; + int m = board.length; + int n = board[0].length; + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + // 从边缘O开始搜索 + boolean isEdge = i == 0 || j == 0 || i == m - 1 || j == n - 1; + if (isEdge && board[i][j] == 'O') { + dfs(board, i, j); + } + } + } + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (board[i][j] == 'O') { + board[i][j] = 'X'; + } + if (board[i][j] == '#') { + board[i][j] = 'O'; + } + } + } + } + + public void dfs(char[][] board, int i, int j) { + if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || board[i][j] == 'X' || board[i][j] == '#') { + // board[i][j] == '#' 说明已经搜索过了. + return; + } + board[i][j] = '#'; + dfs(board, i - 1, j); // 上 + dfs(board, i + 1, j); // 下 + dfs(board, i, j - 1); // 左 + dfs(board, i, j + 1); // 右 + } +} diff --git a/src/pp/arithmetic/leetcode/_131_partition.java b/src/pp/arithmetic/leetcode/_131_partition.java new file mode 100644 index 0000000..1d17ee4 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_131_partition.java @@ -0,0 +1,85 @@ +package pp.arithmetic.leetcode; + +import pp.arithmetic.Util; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by wangpeng on 2019-12-24. + * 131. 分割回文串 + * + * 给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。 + * + * 返回 s 所有可能的分割方案。 + * + * 示例: + * + * 输入: "aab" + * 输出: + * [ + * ["aa","b"], + * ["a","a","b"] + * ] + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/palindrome-partitioning + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _131_partition { + + public static void main(String[] args) { + _131_partition partition = new _131_partition(); + Util.printLists(partition.partition("aab")); + Util.printLists(partition.partition("abbaa")); + Util.printLists(partition.partition("")); + } + + /** + * 解题思路:DFS遍历+回溯 + * 1、DFS遍历,从s的第一位开始,逐步判断至最后一位 + * 2、定义一个skip=1,从1开始,代表从当前位加上skip的结果是否是回文 + * 3、定义一个循环,位置从0开始,得到所有的结果 + * + * 执行用时 :8 ms, 在所有 java 提交中击败了20.05%的用户 + * 内存消耗 :38.1 MB, 在所有 java 提交中击败了97.34%的用户 + * + * @param s + * @return + */ + public List> partition(String s) { + List> retList = new ArrayList<>(); + dfs(retList,new ArrayList<>(),s,0); + return retList; + } + + private void dfs(List> retList, List itemList, String s, int index) { + if (index > s.length()-1){ + retList.add(new ArrayList<>(itemList)); + return; + } + int skip = 1; + while (skip + index <= s.length()) { + String sub = s.substring(index, index + skip); + if (isPlalindrome(sub)) { + itemList.add(sub); + dfs(retList, itemList, s, index + skip); + if (itemList.size() > 0) { + itemList.remove(itemList.size() - 1); + } + } + skip++; + } + } + + //是否是回文 + private boolean isPlalindrome(String s) { + int si = 0, ei = s.length() - 1; + while (si < ei) { + if (s.charAt(si) != s.charAt(ei)) return false; + si++; + ei--; + } + return true; + } +} diff --git a/src/pp/arithmetic/leetcode/_132_minCut.java b/src/pp/arithmetic/leetcode/_132_minCut.java new file mode 100644 index 0000000..f1d3944 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_132_minCut.java @@ -0,0 +1,57 @@ +package pp.arithmetic.leetcode; + +/** + * Created by wangpeng on 2019-12-27. + * 132. 分割回文串 II + * + * 给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。 + * + * 返回符合要求的最少分割次数。 + * + * 示例: + * + * 输入: "aab" + * 输出: 1 + * 解释: 进行一次分割就可将 s 分割成 ["aa","b"] 这样两个回文子串。 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/palindrome-partitioning-ii + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _132_minCut { + + public static void main(String[] args) { + _132_minCut minCut = new _132_minCut(); + System.out.println(minCut.minCut("aab")); + } + + /** + * 解题思路: + * 要求最少分割次数,所以在一次分割中尽可能的形成较长的回文子串,当然你也可以将所有的可能性都列出来,取其中最少的(耗时) + * + * @param s + * @return + */ + public int minCut(String s) { + boolean[][] dp = new boolean[s.length()][s.length()]; + int[] min = new int[s.length()]; + min[0] = 0; + for (int i = 1; i < s.length(); i++) { + int temp = Integer.MAX_VALUE; + for (int j = 0; j <= i; j++) { + if (s.charAt(j) == s.charAt(i) && (j + 1 > i - 1 || dp[j + 1][i - 1])) { + dp[j][i] = true; + if (j == 0) { + temp = 0; + } else { + temp = Math.min(temp, min[j - 1] + 1); + } + } + } + min[i] = temp; + + } + return min[s.length() - 1]; + + } +} diff --git a/src/pp/arithmetic/leetcode/_133_cloneGraph.java b/src/pp/arithmetic/leetcode/_133_cloneGraph.java new file mode 100644 index 0000000..80b8945 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_133_cloneGraph.java @@ -0,0 +1,138 @@ +package pp.arithmetic.leetcode; + + +import java.util.*; + +/** + * Created by wangpeng on 2020-01-20. + * 133. 克隆图 + *

+ * 给你无向 连通 图中一个节点的引用,请你返回该图的 深拷贝(克隆)。 + *

+ * 图中的每个节点都包含它的值 val(int) 和其邻居的列表(list[Node])。 + *

+ * class Node { + * public int val; + * public List neighbors; + * } + *   + *

+ * 测试用例格式: + *

+ * 简单起见,每个节点的值都和它的索引相同。例如,第一个节点值为 1,第二个节点值为 2,以此类推。该图在测试用例中使用邻接列表表示。 + *

+ * 邻接列表是用于表示有限图的无序列表的集合。每个列表都描述了图中节点的邻居集。 + *

+ * 给定节点将始终是图中的第一个节点(值为 1)。你必须将 给定节点的拷贝 作为对克隆图的引用返回。 + *

+ *   + *

+ * 示例 1: + *

+ *

+ *

+ * 输入:adjList = [[2,4],[1,3],[2,4],[1,3]] + * 输出:[[2,4],[1,3],[2,4],[1,3]] + * 解释: + * 图中有 4 个节点。 + * 节点 1 的值是 1,它有两个邻居:节点 2 和 4 。 + * 节点 2 的值是 2,它有两个邻居:节点 1 和 3 。 + * 节点 3 的值是 3,它有两个邻居:节点 2 和 4 。 + * 节点 4 的值是 4,它有两个邻居:节点 1 和 3 。 + * 示例 2: + *

+ *

+ *

+ * 输入:adjList = [[]] + * 输出:[[]] + * 解释:输入包含一个空列表。该图仅仅只有一个值为 1 的节点,它没有任何邻居。 + * 示例 3: + *

+ * 输入:adjList = [] + * 输出:[] + * 解释:这个图是空的,它不含任何节点。 + * 示例 4: + *

+ *

+ *

+ * 输入:adjList = [[2],[1]] + * 输出:[[2],[1]] + *   + *

+ * 提示: + *

+ * 节点数介于 1 到 100 之间。 + * 每个节点值都是唯一的。 + * 无向图是一个简单图,这意味着图中没有重复的边,也没有自环。 + * 由于图是无向的,如果节点 p 是节点 q 的邻居,那么节点 q 也必须是节点 p 的邻居。 + * 图是连通图,你可以从给定节点访问到所有节点。 + *

+ * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/clone-graph + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _133_cloneGraph { + + public static void main(String[] args) { + _133_cloneGraph cloneGraph = new _133_cloneGraph(); + Node node1 = new Node(); + node1.val = 1; + Node node2 = new Node(); + node2.val = 2; + Node node3 = new Node(); + node3.val = 3; + Node node4 = new Node(); + node4.val = 4; + //[[2,4],[1,3],[2,4],[1,3]] + node1.neighbors = new ArrayList<>(); + node1.neighbors.add(node2); + node1.neighbors.add(node4); + node2.neighbors = new ArrayList<>(); + node2.neighbors.add(node1); + node2.neighbors.add(node3); + node3.neighbors = new ArrayList<>(); + node3.neighbors.add(node2); + node3.neighbors.add(node4); + node4.neighbors = new ArrayList<>(); + node4.neighbors.add(node1); + node4.neighbors.add(node3); + Node clone = cloneGraph.cloneGraph(node1); + System.out.println(); + } + + /** + * 解题思路: + * 先花了很大的力气读题目,最后发现就是图的深度遍历,由于每个节点值都是唯一的,用一个HashMap保存遍历过的节点,防止无限循环 + * @param node + * @return + */ + public Node cloneGraph(Node node) { + if (node == null){ + return null; + } + HashMap map = new HashMap<>(); + Node cloneNode = dfs(node, map); + return cloneNode; + } + + private Node dfs(Node node, HashMap map) { + if (map.get(node.val) != null) { + return map.get(node.val); + } + Node cloneNode = new Node(); + cloneNode.val = node.val; + map.put(node.val, cloneNode); + if (node.neighbors != null) { + cloneNode.neighbors = new ArrayList<>(); + for (int i = 0; i < node.neighbors.size(); i++) { + cloneNode.neighbors.add(dfs(node.neighbors.get(i), map)); + } + } + return cloneNode; + } + + private static class Node { + public int val; + public List neighbors; + } +} diff --git a/src/pp/arithmetic/leetcode/_66_plusOne.java b/src/pp/arithmetic/leetcode/_66_plusOne.java new file mode 100644 index 0000000..4a52270 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_66_plusOne.java @@ -0,0 +1,71 @@ +package pp.arithmetic.leetcode; + +import pp.arithmetic.Util; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by wangpeng on 2019-10-19. + * 66. 加一 + *

+ * 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。 + *

+ * 最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。 + *

+ * 你可以假设除了整数 0 之外,这个整数不会以零开头。 + *

+ * 示例 1: + *

+ * 输入: [1,2,3] + * 输出: [1,2,4] + * 解释: 输入数组表示数字 123。 + * 示例 2: + *

+ * 输入: [4,3,2,1] + * 输出: [4,3,2,2] + * 解释: 输入数组表示数字 4321。 + *

+ * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/plus-one + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _66_plusOne { + + public static void main(String[] args) { + _66_plusOne plusOne = new _66_plusOne(); + Util.printArray(plusOne.plusOne(new int[]{1, 2, 3})); + Util.printArray(plusOne.plusOne(new int[]{4, 3, 2, 1})); + Util.printArray(plusOne.plusOne(new int[]{9, 9, 9})); + Util.printArray(plusOne.plusOne(new int[]{0})); + Util.printArray(plusOne.plusOne(new int[]{9})); + } + + /** + * 解题思路: + * 一道算数加法+1,需要注意两种情况: + * 1、低位向高位进位 ==> 从末尾开始遍历 + * 2、整数头需要进位 ==> 构建一个新数组保存返回结果 + * + * @param digits + * @return + */ + public int[] plusOne(int[] digits) { + List retList = new ArrayList<>(); + int highAdd = 1; //进位 + for (int i = digits.length - 1; i >= 0; i--) { + int newDigit = digits[i] + highAdd; + highAdd = newDigit / 10; + newDigit = newDigit % 10; + retList.add(0, newDigit); + } + if (highAdd > 0) retList.add(0, highAdd); + //listToArr + int[] retArr = new int[retList.size()]; + for (int i = 0; i < retList.size(); i++) { + retArr[i] = retList.get(i); + } + + return retArr; + } +} diff --git a/src/pp/arithmetic/leetcode/_67_addBinary.java b/src/pp/arithmetic/leetcode/_67_addBinary.java new file mode 100644 index 0000000..fc0eec9 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_67_addBinary.java @@ -0,0 +1,69 @@ +package pp.arithmetic.leetcode; + +/** + * Created by wangpeng on 2019-10-21. + * 67. 二进制求和 + *

+ * 给定两个二进制字符串,返回他们的和(用二进制表示)。 + *

+ * 输入为非空字符串且只包含数字 1 和 0。 + *

+ * 示例 1: + *

+ * 输入: a = "11", b = "1" + * 输出: "100" + * 示例 2: + *

+ * 输入: a = "1010", b = "1011" + * 输出: "10101" + *

+ * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/add-binary + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _67_addBinary { + + public static void main(String[] args) { + _67_addBinary addBinary = new _67_addBinary(); + System.out.println(addBinary.addBinary("11", "1")); + System.out.println(addBinary.addBinary("1010", "1011")); + System.out.println(addBinary.addBinary("1111", "1111")); + } + + /** + * 解题思路: + * 从低位开始累加,注意两边字符串不一致,提高执行效率不要使用StringBuilder + * + * 执行用时 :1 ms, 在所有 java 提交中击败了100.00%的用户 + * 内存消耗 :36 MB, 在所有 java 提交中击败了55.45%的用户 + * + * @param a + * @param b + * @return + */ + public String addBinary(String a, String b) { + int i = a.length() - 1; + int j = b.length() - 1; + int carry = 0; + char[] result = new char[Math.max(i, j) + 1]; + int pos = result.length - 1; + while (i >= 0 || j >= 0) { + int sum = carry; + if (i >= 0) { + sum += a.charAt(i--) - '0'; + } + if (j >= 0) { + sum += b.charAt(j--) - '0'; + } + //>>1 代表 /2,进位 + carry = sum >> 1; + //sum & 0x01 ==> 进位后只取低位 + result[pos--] = (char) ((sum & 0x01) + '0'); + } + if (carry > 0) { //最后有进位,直接进行数据拼接,防止数组越界 + return "1" + String.valueOf(result); + } + return String.valueOf(result); + } +} + diff --git a/src/pp/arithmetic/leetcode/_68_fullJustify.java b/src/pp/arithmetic/leetcode/_68_fullJustify.java new file mode 100644 index 0000000..7758884 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_68_fullJustify.java @@ -0,0 +1,178 @@ +package pp.arithmetic.leetcode; + +import pp.arithmetic.Util; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by wangpeng on 2019-10-22. + * 68. 文本左右对齐 + * + * 给定一个单词数组和一个长度 maxWidth,重新排版单词,使其成为每行恰好有 maxWidth 个字符,且左右两端对齐的文本。 + * + * 你应该使用“贪心算法”来放置给定的单词;也就是说,尽可能多地往每行中放置单词。必要时可用空格 ' ' 填充,使得每行恰好有 maxWidth 个字符。 + * + * 要求尽可能均匀分配单词间的空格数量。如果某一行单词间的空格不能均匀分配,则左侧放置的空格数要多于右侧的空格数。 + * + * 文本的最后一行应为左对齐,且单词之间不插入额外的空格。 + * + * 说明: + * + * 单词是指由非空格字符组成的字符序列。 + * 每个单词的长度大于 0,小于等于 maxWidth。 + * 输入单词数组 words 至少包含一个单词。 + * 示例: + * + * 输入: + * words = ["This", "is", "an", "example", "of", "text", "justification."] + * maxWidth = 16 + * 输出: + * [ + *    "This    is    an", + *    "example  of text", + *    "justification.  " + * ] + * 示例 2: + * + * 输入: + * words = ["What","must","be","acknowledgment","shall","be"] + * maxWidth = 16 + * 输出: + * [ + *   "What   must   be", + *   "acknowledgment  ", + *   "shall be        " + * ] + * 解释: 注意最后一行的格式应为 "shall be " 而不是 "shall be", + *   因为最后一行应为左对齐,而不是左右两端对齐。 + * 第二行同样为左对齐,这是因为这行只包含一个单词。 + * 示例 3: + * + * 输入: + * words = ["Science","is","what","we","understand","well","enough","to","explain", + *   "to","a","computer.","Art","is","everything","else","we","do"] + * maxWidth = 20 + * 输出: + * [ + *   "Science  is  what we", + * "understand      well", + *   "enough to explain to", + *   "a  computer.  Art is", + *   "everything  else  we", + *   "do                  " + * ] + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/text-justification + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _68_fullJustify { + + public static void main(String[] args) { + _68_fullJustify fullJustify = new _68_fullJustify(); + Util.printStringList(fullJustify.fullJustify(new String[]{"This", "is", "an", "example", "of", "text", "justification."},16)); + Util.printStringList(fullJustify.fullJustify(new String[]{"What","must","be","acknowledgment","shall","be"},16)); + Util.printStringList(fullJustify.fullJustify(new String[]{"Science","is","what","we","understand","well","enough","to","explain", "to","a","computer.","Art","is","everything","else","we","do"},20)); + } + + /** + * 解题思路: + * 大致想法:先确定一行放几个单词,再跟根据条件对单词进行排序 + * 1、一行能放几个单词: + * 1.1:一个单词放下去之后占的位置是length+1(单词和单词直接至少有一个空格) + * 1.2:按照1.1的规则循环直到需要的长度>maxWidth + * 2、跟根据条件对单词进行排序: + * 2.1:对于只有一个单词的行,直接从左开始摆放 + * 2.2:对于只有2个单词的行,最左和最右摆放 + * 2.3:对于多余2个单词的行,先计算单词直接平均空格有多少个,剩余空格从左到右一个单词后逐个排布(肯定不会超过总单词数) + * 2.4:如是最后一行,则直接从左开始排序 + *

+ * 存储结构:maxWidth长度的数组保存 + * + * 执行用时 :1 ms, 在所有 java 提交中击败了99.05%的用户 + * 内存消耗 :34.9 MB, 在所有 java 提交中击败了40.26%的用户 + * + * @param words + * @param maxWidth + * @return + */ + public List fullJustify(String[] words, int maxWidth) { + List retList = new ArrayList<>(); + List lineList = new ArrayList<>(); + int leftWidth = maxWidth; + for (int i = 0; i < words.length; i++) { + String word = words[i]; + int wordWidth = word.length(); + if (leftWidth - wordWidth - lineList.size() < 0) { + //超过了需要换行了 + retList.add(handleSort(lineList, leftWidth, false)); + //换行重置 + leftWidth = maxWidth; + lineList.clear(); + } + lineList.add(word); + leftWidth -= wordWidth; + } + if (lineList.size()>0){ + retList.add(handleSort(lineList, leftWidth, true)); + } + + return retList; + } + + /** + * 2.1:对于只有一个单词的行,直接从左开始摆放 + * 2.2:对于只有2个单词的行,最左和最右摆放 + * 2.3:对于多余2个单词的行,先计算单词直接平均空格有多少个,剩余空格从左到右一个单词后逐个排布(肯定不会超过总单词数) + * 2.4:如是最后一行,则直接从左开始排序 + * + * @param lineList + * @param leftWidth + * @param isLastLine + * @return + */ + private String handleSort(List lineList, int leftWidth, boolean isLastLine) { + StringBuilder builder = new StringBuilder(); + if (isLastLine) { + for (int i = 0; i < lineList.size(); i++) { + builder.append(lineList.get(i)); + if (i != lineList.size() - 1) { + builder.append(" "); + leftWidth--; + } else { + for (int j = 0; j < leftWidth; j++) { + builder.append(" "); + } + } + } + } else { + //剩余空格数 + int empty = leftWidth; + //相等空格数 + int equalEmpty; + //左侧多余空格数 + int leftEmpty; + if (lineList.size() == 1) { + equalEmpty = empty; + leftEmpty = 0; + } else { + equalEmpty = empty / (lineList.size() - 1); + leftEmpty = empty % (lineList.size() - 1); + } + for (int i = 0; i < lineList.size(); i++) { + builder.append(lineList.get(i)); + if (i != lineList.size() - 1 || lineList.size() == 1) { + for (int j = 0; j < equalEmpty; j++) { + builder.append(" "); + } + if (leftEmpty-- > 0) { + builder.append(" "); + } + } + } + } + + return builder.toString(); + } +} diff --git a/src/pp/arithmetic/leetcode/_73_setZeroes.java b/src/pp/arithmetic/leetcode/_73_setZeroes.java new file mode 100644 index 0000000..9575df4 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_73_setZeroes.java @@ -0,0 +1,121 @@ +package pp.arithmetic.leetcode; + +/** + * Created by wangpeng on 2019-10-23. + * 73. 矩阵置零 + * + * 给定一个 m x n 的矩阵,如果一个元素为 0,则将其所在行和列的所有元素都设为 0。请使用原地算法。 + * + * 示例 1: + * + * 输入: + * [ + *   [1,1,1], + *   [1,0,1], + *   [1,1,1] + * ] + * 输出: + * [ + *   [1,0,1], + *   [0,0,0], + *   [1,0,1] + * ] + * 示例 2: + * + * 输入: + * [ + *   [0,1,2,0], + *   [3,4,5,2], + *   [1,3,1,5] + * ] + * 输出: + * [ + *   [0,0,0,0], + *   [0,4,5,0], + *   [0,3,1,0] + * ] + * 进阶: + * + * 一个直接的解决方案是使用  O(mn) 的额外空间,但这并不是一个好的解决方案。 + * 一个简单的改进方案是使用 O(m + n) 的额外空间,但这仍然不是最好的解决方案。 + * 你能想出一个常数空间的解决方案吗? + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/set-matrix-zeroes + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _73_setZeroes { + + public static void main(String[] args) { + _73_setZeroes setZeroes = new _73_setZeroes(); + int[][] matrix = new int[][]{ + {1, 1, 1}, + {0, 1, 2} + }; + setZeroes.setZeroes(matrix); + int[][] matrix1 = new int[][]{ + {1, 1, 1}, + {1, 0, 1}, + {1, 1, 1} + }; + setZeroes.setZeroes(matrix1); + int[][] matrix2 = new int[][]{ + {0, 1, 2, 0}, + {3, 4, 5, 2}, + {1, 3, 1, 5} + }; + setZeroes.setZeroes(matrix2); + } + + /** + * 难点在于:使用常数空间,我们先来看不适用常数空间咋解决 + * O(mn):直接生成一个同等大小的矩阵,遍历原始矩阵,遇0将新矩阵横竖都设置为0 + * O(m+n):两个set分别保存有0的横和竖列,遍历结束直接将set中的横竖设0 + * 解题思路: + * 1、利用矩阵的第一行和第一列保存有0的行和列 + * 2、需要考虑下特殊情况的[0,0],这个位置可能是横列、纵列、自身导致赋的0 + * + * 执行用时 :1 ms, 在所有 java 提交中击败了100.00%的用户 + * 内存消耗 :43.3 MB, 在所有 java 提交中击败了97.83%的用户 + * + * @param matrix + */ + public void setZeroes(int[][] matrix) { + boolean isCol = false; + int row = matrix.length; + int col = matrix[0].length; + + //使用第一行、第一列标记0 + for (int i = 0; i < row; i++) { + if (matrix[i][0] == 0) { + isCol = true; + } + for (int j = 1; j < col; j++) { + if (matrix[i][j] == 0) { + matrix[i][0] = 0; + matrix[0][j] = 0; + } + } + } + //横、竖列置0 + for (int i = 1; i < row; i++) { + for (int j = 1; j < col; j++) { + if (matrix[i][0] ==0 || matrix[0][j] == 0) { + matrix[i][j] = 0; + } + } + } + //[0,0]为0的时候,需要特殊判断下是横还是纵 + if (matrix[0][0] == 0) { + for (int j = 0; j < col; j++) { + matrix[0][j] = 0; + } + } + + if (isCol) { + for (int i = 0; i < row; i++) { + matrix[i][0] = 0; + } + } + } +} diff --git a/src/pp/arithmetic/leetcode/_74_searchMatrix.java b/src/pp/arithmetic/leetcode/_74_searchMatrix.java new file mode 100644 index 0000000..e63ee26 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_74_searchMatrix.java @@ -0,0 +1,107 @@ +package pp.arithmetic.leetcode; + +/** + * Created by wangpeng on 2019-10-24. + * 74. 搜索二维矩阵 + * + * 编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性: + * + * 每行中的整数从左到右按升序排列。 + * 每行的第一个整数大于前一行的最后一个整数。 + * 示例 1: + * + * 输入: + * matrix = [ + * [1, 3, 5, 7], + * [10, 11, 16, 20], + * [23, 30, 34, 50] + * ] + * target = 3 + * 输出: true + * 示例 2: + * + * 输入: + * matrix = [ + * [1, 3, 5, 7], + * [10, 11, 16, 20], + * [23, 30, 34, 50] + * ] + * target = 13 + * 输出: false + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/search-a-2d-matrix + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _74_searchMatrix { + + public static void main(String[] args) { + int[][] matrix = new int[][]{ + {1, 3, 5, 7}, + {10, 11, 16, 20}, + {23, 30, 34, 50} + }; + _74_searchMatrix searchMatrix = new _74_searchMatrix(); + System.out.println(searchMatrix.searchMatrix(matrix,1)); + System.out.println(searchMatrix.searchMatrix(matrix,3)); + System.out.println(searchMatrix.searchMatrix(matrix,5)); + System.out.println(searchMatrix.searchMatrix(matrix,7)); + System.out.println(searchMatrix.searchMatrix(matrix,10)); + System.out.println(searchMatrix.searchMatrix(matrix,11)); + System.out.println(searchMatrix.searchMatrix(matrix,16)); + System.out.println(searchMatrix.searchMatrix(matrix,20)); + System.out.println(searchMatrix.searchMatrix(matrix,23)); + System.out.println(searchMatrix.searchMatrix(matrix,50)); + System.out.println(searchMatrix.searchMatrix(matrix,13)); + System.out.println(searchMatrix.searchMatrix(matrix,40)); + } + + /** + * 解题思路: + * 整个矩阵类似一个有序的升序数组,考虑使用二分查找是否存在目标值 + * 难点:中间点的计算 + * 1.利用公式计算起点和终点之间的差:(ex - sx) * col + ey - sy, + * 2.中间点距离起点的步数:ml = ((ex - sx) * col + ey - sy) / 2 + * 3.mx = sx + (ml + sy) / col <== 起点+偏移计算出中间点的x + * 4.my = ml + sy - (mx - sx) * col <== 根据第一步的公式,代入mx,计算出my + * 5.利用二分查找的规则判断出结果 + * + * 执行用时 :0 ms, 在所有 java 提交中击败了100.00%的用户 + * 内存消耗 :42.6 MB, 在所有 java 提交中击败了39.56%的用户 + * + * @param matrix + * @param target + * @return + */ + public boolean searchMatrix(int[][] matrix, int target) { + if (matrix == null || matrix.length == 0) return false; + int row = matrix.length; + int col = matrix[0].length; + if (col == 0) return false; + int sx = 0, sy = 0, ex = row - 1, ey = col - 1; + if (target < matrix[sx][sy] || target > matrix[ex][ey]) return false; + int mx, my, ml; + while (sx * col + sy <= ex * col + ey) { + //计算中间点 + ml = ((ex - sx) * col + ey - sy) / 2; + mx = sx + (ml + sy) / col; + my = ml + sy - (mx - sx) * col; + int middle = matrix[mx][my]; + if (middle == target) return true; + //防止无法退出 + if (ml == 0) { + if (matrix[ex][ey] == target) return true; + return false; + } + if (middle > target) { + ex = mx; + ey = my; + } else { + sx = mx; + sy = my; + } + } + + return false; + } +} diff --git a/src/pp/arithmetic/leetcode/_81_search.java b/src/pp/arithmetic/leetcode/_81_search.java new file mode 100644 index 0000000..fe1de19 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_81_search.java @@ -0,0 +1,71 @@ +package pp.arithmetic.leetcode; + +/** + * Created by wangpeng on 2019-10-25. + * 81. 搜索旋转排序数组 II + * + * 假设按照升序排序的数组在预先未知的某个点上进行了旋转。 + * + * ( 例如,数组 [0,0,1,2,2,5,6] 可能变为 [2,5,6,0,0,1,2] )。 + * + * 编写一个函数来判断给定的目标值是否存在于数组中。若存在返回 true,否则返回 false。 + * + * 示例 1: + * + * 输入: nums = [2,5,6,0,0,1,2], target = 0 + * 输出: true + * 示例 2: + * + * 输入: nums = [2,5,6,0,0,1,2], target = 3 + * 输出: false + * 进阶: + * + * 这是 搜索旋转排序数组 的延伸题目,本题中的 nums  可能包含重复元素。 + * 这会影响到程序的时间复杂度吗?会有怎样的影响,为什么? + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/search-in-rotated-sorted-array-ii + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _81_search { + + public static void main(String[] args) { + _81_search search = new _81_search(); + System.out.println(search.search(new int[]{2, 5, 6, 0, 0, 1, 2}, 0)); + System.out.println(search.search(new int[]{2, 5, 6, 0, 0, 1, 2}, 4)); + System.out.println(search.search(new int[]{1, 1, 3, 1}, 3)); + System.out.println(search.search(new int[]{3, 1, 1}, 3)); + } + + /** + * 解题思路: + * 整体解法类似 {@link _33_search},有序的数组使用二分查找效率最高,注意相同位置的判断 + * + * @param nums + * @param target + * @return + */ + public boolean search(int[] nums, int target) { + int left = 0; + int right = nums.length - 1; + while (left <= right) { + int mid = left + (right - left) / 2; + if (nums[mid] == target) return true; + if (nums[left] == nums[mid] && nums[mid] == nums[right]) { + left++; + right--; + } else if (nums[left] <= nums[mid]) { //确定左区间 + if (nums[left] <= target && target < nums[mid]) + right = mid - 1; + else + left = mid + 1; + } else { //确定右区间 + if (nums[mid] < target && target <= nums[right]) + left = mid + 1; + else + right = mid - 1; + } + } + return false; + } +} diff --git a/src/pp/arithmetic/leetcode/_82_deleteDuplicates.java b/src/pp/arithmetic/leetcode/_82_deleteDuplicates.java new file mode 100644 index 0000000..879d121 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_82_deleteDuplicates.java @@ -0,0 +1,93 @@ +package pp.arithmetic.leetcode; + +import pp.arithmetic.Util; +import pp.arithmetic.model.ListNode; + +/** + * Created by wangpeng on 2019-10-31. + * 82. 删除排序链表中的重复元素 II + * + * 给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。 + * + * 示例 1: + * + * 输入: 1->2->3->3->4->4->5 + * 输出: 1->2->5 + * 示例 2: + * + * 输入: 1->1->1->2->3 + * 输出: 2->3 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _82_deleteDuplicates { + + public static void main(String[] args) { + _82_deleteDuplicates deleteDuplicates = new _82_deleteDuplicates(); + //1->2->3->3->4->4->5 + ListNode head1 = new ListNode(1); + head1.next = new ListNode(2); + head1.next.next = new ListNode(3); + head1.next.next.next = new ListNode(3); + head1.next.next.next.next = new ListNode(4); + head1.next.next.next.next.next = new ListNode(4); + head1.next.next.next.next.next.next = new ListNode(5); + Util.printListNode(deleteDuplicates.deleteDuplicates(head1)); + //1->1->1->2->3 + ListNode head2 = new ListNode(1); + head2.next = new ListNode(1); + head2.next.next = new ListNode(1); + head2.next.next.next = new ListNode(2); + head2.next.next.next.next = new ListNode(3); + Util.printListNode(deleteDuplicates.deleteDuplicates(head2)); + } + + /** + * 解题思路: + * 对于链表类型的题目,就是按照next的指针进行遍历,找到题目要求 + * 1、定义四个指针: + * 一个头结点的前置虚拟指针==>方便返回结果的头结点, + * 一个前置指针==>方便切断遍历相同节点, + * 一个遍历指针, + * 一个搜寻相同指针的尾结点==>定位结尾 + * 2、找到满足条件的,将前置指针的next指向尾结点的next + * + * 执行用时 :1 ms, 在所有 java 提交中击败了99.26%的用户 + * 内存消耗 :37 MB, 在所有 java 提交中击败了57.65%的用户 + * + * @param head + * @return + */ + public ListNode deleteDuplicates(ListNode head) { + //头结点的前置虚拟指针 + ListNode dummy = new ListNode(0); + dummy.next = head; + //前置指针 + ListNode preNode = head; + //遍历指针 + ListNode node = head; + //尾结点指针 + ListNode endNode ; + while (node != null ) { + endNode = node.next; + while (endNode != null && endNode.val == node.val) { + endNode = endNode.next; + } + if (node.next == endNode){ + //不是重复的 + preNode = node; + }else{ + //存在重复的 + preNode.next = endNode; + if (dummy.next == node){ + dummy.next = endNode; + } + } + node = endNode; + } + + return dummy.next; + } +} diff --git a/src/pp/arithmetic/leetcode/_83_deleteDuplicates.java b/src/pp/arithmetic/leetcode/_83_deleteDuplicates.java new file mode 100644 index 0000000..ff232d3 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_83_deleteDuplicates.java @@ -0,0 +1,63 @@ +package pp.arithmetic.leetcode; + +import pp.arithmetic.Util; +import pp.arithmetic.model.ListNode; + +/** + * Created by wangpeng on 2019-11-04. + * 83. 删除排序链表中的重复元素 + * + * 给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。 + * + * 示例 1: + * + * 输入: 1->1->2 + * 输出: 1->2 + * 示例 2: + * + * 输入: 1->1->2->3->3 + * 输出: 1->2->3 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _83_deleteDuplicates { + + public static void main(String[] args) { + _83_deleteDuplicates deleteDuplicates = new _83_deleteDuplicates(); + ListNode node = new ListNode(1); + node.next = new ListNode(1); + node.next.next = new ListNode(2); + Util.printListNode(deleteDuplicates.deleteDuplicates(node)); + ListNode node1 = new ListNode(1); + node1.next = new ListNode(1); + node1.next.next = new ListNode(2); + node1.next.next.next = new ListNode(3); + node1.next.next.next.next = new ListNode(3); + Util.printListNode(deleteDuplicates.deleteDuplicates(node1)); + } + + /** + * 解题思路:典型的列表遍历 + * + * @param head + * @return + */ + public ListNode deleteDuplicates(ListNode head) { + ListNode dummy = new ListNode(0); + dummy.next = head; + ListNode next = head; + ListNode preEqual; + while (next != null) { + preEqual = next.next; + while (preEqual!=null&&preEqual.val == next.val){ + preEqual = preEqual.next; + } + next.next = preEqual; + next = preEqual; + } + + return dummy.next; + } +} diff --git a/src/pp/arithmetic/leetcode/_87_isScramble.java b/src/pp/arithmetic/leetcode/_87_isScramble.java new file mode 100644 index 0000000..82e2664 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_87_isScramble.java @@ -0,0 +1,110 @@ +package pp.arithmetic.leetcode; + +/** + * Created by wangpeng on 2019-11-05. + * 87. 扰乱字符串 + * + * 下图是字符串 s1 = "great" 的一种可能的表示形式。 + * + * great + * / \ + * gr eat + * / \ / \ + * g r e at + * / \ + * a t + * 在扰乱这个字符串的过程中,我们可以挑选任何一个非叶节点,然后交换它的两个子节点。 + * + * 例如,如果我们挑选非叶节点 "gr" ,交换它的两个子节点,将会产生扰乱字符串 "rgeat" 。 + * + * rgeat + * / \ + * rg eat + * / \ / \ + * r g e at + * / \ + * a t + * 我们将 "rgeat” 称作 "great" 的一个扰乱字符串。 + * + * 同样地,如果我们继续交换节点 "eat" 和 "at" 的子节点,将会产生另一个新的扰乱字符串 "rgtae" 。 + * + * rgtae + * / \ + * rg tae + * / \ / \ + * r g ta e + * / \ + * t a + * 我们将 "rgtae” 称作 "great" 的一个扰乱字符串。 + * + * 给出两个长度相等的字符串 s1 和 s2,判断 s2 是否是 s1 的扰乱字符串。 + * + * 示例 1: + * + * 输入: s1 = "great", s2 = "rgeat" + * 输出: true + * 示例 2: + * + * 输入: s1 = "abcde", s2 = "caebd" + * 输出: false + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/scramble-string + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _87_isScramble { + + public static void main(String[] args) { + _87_isScramble isScramble = new _87_isScramble(); + System.out.println(isScramble.isScramble("great","rgeat")); + System.out.println(isScramble.isScramble("abcde","caebd")); + } + + /** + * 解题思路: + * 对于两个字符串,比较是否相等,有两种情景 + * 1:字符串本身就相等 + * 2:基于某个节点交换后相等==>此种情况可以将旋转后的子字符串代入第一种情况进行判断 + * + * 对于上述两种情况可以将字符串分解成两部分(从0开始拆解) + * + * @param s1 + * @param s2 + * @return + */ + public boolean isScramble(String s1, String s2) { + if (s1.length() != s2.length()) { + return false; + } + if (s1.equals(s2)) { + return true; + } + + //判断两个字符串每个字母出现的次数是否一致 + int[] letters = new int[26]; + for (int i = 0; i < s1.length(); i++) { + letters[s1.charAt(i) - 'a']++; + letters[s2.charAt(i) - 'a']--; + } + //如果两个字符串的字母出现不一致直接返回 false + for (int i = 0; i < 26; i++) { + if (letters[i] != 0) { + return false; + } + } + + //遍历每个切割位置 + for (int i = 1; i < s1.length(); i++) { + //对应情况 1 ,判断 S1 的子树能否变为 S2 相应部分 + if (isScramble(s1.substring(0, i), s2.substring(0, i)) && isScramble(s1.substring(i), s2.substring(i))) { + return true; + } + //对应情况 2 ,S1 两个子树先进行了交换,然后判断 S1 的子树能否变为 S2 相应部分 + if (isScramble(s1.substring(i), s2.substring(0, s2.length() - i)) && + isScramble(s1.substring(0, i), s2.substring(s2.length() - i)) ) { + return true; + } + } + return false; + } +} diff --git a/src/pp/arithmetic/leetcode/_88_merge.java b/src/pp/arithmetic/leetcode/_88_merge.java new file mode 100644 index 0000000..1719058 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_88_merge.java @@ -0,0 +1,69 @@ +package pp.arithmetic.leetcode; + +import pp.arithmetic.Util; + +/** + * Created by wangpeng on 2019-11-07. + * 88. 合并两个有序数组 + * + * 给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。 + * + * 说明: + * + * 初始化 nums1 和 nums2 的元素数量分别为 m 和 n。 + * 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。 + * 示例: + * + * 输入: + * nums1 = [1,2,3,0,0,0], m = 3 + * nums2 = [2,5,6], n = 3 + * + * 输出: [1,2,2,3,5,6] + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/merge-sorted-array + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _88_merge { + + public static void main(String[] args) { + _88_merge merge = new _88_merge(); + int[] nums1 = new int[]{1, 2, 3, 0, 0, 0, 0, 0}; + int[] nums2 = new int[]{1, 1, 2, 5, 6}; + merge.merge(nums1, 0, nums2, 5); + Util.printArray(nums1); + } + + /** + * 解题思路: + * 同时遍历两个数组,比较各自的大小,插入到相应的位置,由于nums1有额外的位置,所以从后面开始插入大元素可以减少元素的移动 + * + * @param nums1 + * @param m + * @param nums2 + * @param n + */ + public void merge(int[] nums1, int m, int[] nums2, int n) { + while (m > 0 || n > 0) { + int numM; + int numN; + if (m > 0 && n > 0) { + numM = nums1[m - 1]; + numN = nums2[n - 1]; + if (numM > numN) { + nums1[m + n - 1] = numM; + m--; + } else { + nums1[m + n - 1] = numN; + n--; + } + } else if (m > 0) { + //只剩下nums1,肯定是有序的 + break; + } else { + nums1[n - 1] = nums2[n - 1]; + n--; + } + } + } +} diff --git a/src/pp/arithmetic/leetcode/_89_grayCode.java b/src/pp/arithmetic/leetcode/_89_grayCode.java new file mode 100644 index 0000000..2abc394 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_89_grayCode.java @@ -0,0 +1,71 @@ +package pp.arithmetic.leetcode; + +import pp.arithmetic.Util; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by wangpeng on 2019-11-09. + * 89. 格雷编码 + *

+ * 格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。 + *

+ * 给定一个代表编码总位数的非负整数 n,打印其格雷编码序列。格雷编码序列必须以 0 开头。 + *

+ * 示例 1: + *

+ * 输入: 2 + * 输出: [0,1,3,2] + * 解释: + * 00 - 0 + * 01 - 1 + * 11 - 3 + * 10 - 2 + *

+ * 对于给定的 n,其格雷编码序列并不唯一。 + * 例如,[0,2,3,1] 也是一个有效的格雷编码序列。 + *

+ * 00 - 0 + * 10 - 2 + * 11 - 3 + * 01 - 1 + * 示例 2: + *

+ * 输入: 0 + * 输出: [0] + * 解释: 我们定义格雷编码序列必须以 0 开头。 + *   给定编码总位数为 n 的格雷编码序列,其长度为 2^n。当 n = 0 时,长度为 2^0 = 1。 + *   因此,当 n = 0 时,其格雷编码序列为 [0]。 + *

+ * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/gray-code + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _89_grayCode { + + public static void main(String[] args) { + _89_grayCode grayCode = new _89_grayCode(); + Util.printList(grayCode.grayCode(2)); + } + + /** + * 解题思路: + * + * @param n + * @return + */ + public List grayCode(int n) { + List gray = new ArrayList<>(); + gray.add(0); //初始化 n = 0 的解 + for (int i = 0; i < n; i++) { + int add = 1 << i; //要加的数 + //倒序遍历,并且加上一个值添加到结果中 + for (int j = gray.size() - 1; j >= 0; j--) { + gray.add(gray.get(j) + add); + } + } + return gray; + } + +} diff --git a/src/pp/arithmetic/leetcode/_96_numTrees.java b/src/pp/arithmetic/leetcode/_96_numTrees.java new file mode 100644 index 0000000..934d2f7 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_96_numTrees.java @@ -0,0 +1,97 @@ +package pp.arithmetic.leetcode; + +/** + * Created by wangpeng on 2019-12-04. + * + * 给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种? + * + * 示例: + * + * 输入: 3 + * 输出: 5 + * 解释: + * 给定 n = 3, 一共有 5 种不同结构的二叉搜索树: + * + * 1 3 3 2 1 + * \ / / / \ \ + * 3 2 1 1 3 2 + * / / \ \ + * 2 1 2 3 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/unique-binary-search-trees + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _96_numTrees { + + public static void main(String[] args) { + _96_numTrees numTrees = new _96_numTrees(); + System.out.println(numTrees.numTrees(1)); + System.out.println(numTrees.numTrees(2)); + System.out.println(numTrees.numTrees(3)); + System.out.println(numTrees.numTrees(4)); + System.out.println(numTrees.numTrees(5)); + } + + /** + * 解法一:{@link _96_numTrees#dfs(int, int)},直接利用DFS进行求解,待优化 + * 解法二:{@link _96_numTrees#dp(int)},将二叉树编译转换为动态规范转换 + * + * @param n + * @return + */ + public int numTrees(int n) { + return dp(n); + } + + /** + * 解题思路(动态规划) + * 1、将大问题转换为小问题:第i位的个数,再求和 + * 2、第i位的个数 += dp[j](左) * dp[i - j - 1](右) (j=0,j= ei) return 1; + int sum = 0; + for (int i = si; i <= ei; i++) { + int leftCount = dfs(si, i - 1); + int rightCount = dfs(i + 1, ei); + sum += (leftCount * rightCount); + } + return sum; + } +} diff --git a/src/pp/arithmetic/leetcode/_97_isInterleave.java b/src/pp/arithmetic/leetcode/_97_isInterleave.java new file mode 100644 index 0000000..4862a18 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_97_isInterleave.java @@ -0,0 +1,65 @@ +package pp.arithmetic.leetcode; + +/** + * Created by wangpeng on 2019-11-27. + * 97. 交错字符串 + *

+ * 给定三个字符串 s1, s2, s3, 验证 s3 是否是由 s1 和 s2 交错组成的。 + *

+ * 示例 1: + *

+ * 输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" + * 输出: true + * 示例 2: + *

+ * 输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc" + * 输出: false + *

+ * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/interleaving-string + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _97_isInterleave { + + public static void main(String[] args) { + _97_isInterleave isInterleave = new _97_isInterleave(); + System.out.println(isInterleave.isInterleave("a", "bbbbbbb", "abbbbbba")); + System.out.println(isInterleave.isInterleave("aabcc", "dbbca", "aadbbcbcac")); + System.out.println(isInterleave.isInterleave("aabcc", "dbbca", "aadbbbaccc")); + System.out.println(isInterleave.isInterleave("a", "", "c")); + System.out.println(isInterleave.isInterleave("ab", "bc", "bbac")); + } + + /** + * 解题思路:循环比较,回溯算法 + * 先比较第i位+比较后面的位,如果第i位后面的都能匹配上,加上第i位也能匹配上,那么就能完全匹配。i从0开始 + * + * 执行用时 :1362 ms, 在所有 java 提交中击败了5.10%的用户 + * 内存消耗 :34.7 MB, 在所有 java 提交中击败了42.29%的用户 + * + * @param s1、 + * @param s2 + * @param s3 + * @return + */ + public boolean isInterleave(String s1, String s2, String s3) { + if (s3.length() != s1.length() + s2.length()) return false; + return isInterleave(s1, s2, s3, 0, 0, 0); + } + + private boolean isInterleave(String s1, String s2, String s3, int i1, int i2, int i3) { + if (i3 == s3.length()) return true; + char c3 = s3.charAt(i3); + if (((i1 < s1.length() && s1.charAt(i1) != c3) || "".equals(s1)) && + ((i2 < s2.length() && s2.charAt(i2) != c3) || "".equals(s2))) { + return false; + } + if (i1 < s1.length() && s1.charAt(i1) == c3 && isInterleave(s1, s2, s3, i1 + 1, i2, i3 + 1)) { + return true; + } + if (i2 < s2.length() && s2.charAt(i2) == c3 && isInterleave(s1, s2, s3, i1, i2 + 1, i3 + 1)) { + return true; + } + return false; + } +} diff --git a/src/pp/arithmetic/leetcode/_99_recoverTree.java b/src/pp/arithmetic/leetcode/_99_recoverTree.java new file mode 100644 index 0000000..50d5d6e --- /dev/null +++ b/src/pp/arithmetic/leetcode/_99_recoverTree.java @@ -0,0 +1,153 @@ +package pp.arithmetic.leetcode; + +import pp.arithmetic.Util; +import pp.arithmetic.model.TreeNode; + +/** + * Created by wangpeng on 2019-12-01. + * 99. 恢复二叉搜索树 + * + * 二叉搜索树中的两个节点被错误地交换。 + * + * 请在不改变其结构的情况下,恢复这棵树。 + * + * 示例 1: + * + * 输入: [1,3,null,null,2] + * + *   1 + *   / + *  3 + *   \ + *   2 + * + * 输出: [3,1,null,null,2] + * + *   3 + *   / + *  1 + *   \ + *   2 + * 示例 2: + * + * 输入: [3,1,4,null,null,2] + * + * 3 + * / \ + * 1 4 + *   / + *   2 + * + * 输出: [2,1,4,null,null,3] + * + * 2 + * / \ + * 1 4 + *   / + *  3 + * 进阶: + * + * 使用 O(n) 空间复杂度的解法很容易实现。 + * 你能想出一个只使用常数空间的解决方案吗? + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/recover-binary-search-tree + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _99_recoverTree { + + public static void main(String[] args) { + TreeNode treeNode = new TreeNode(1); + treeNode.left = new TreeNode(3); + treeNode.left.right = new TreeNode(2); + _99_recoverTree recoverTree = new _99_recoverTree(); + recoverTree.recoverTree(treeNode); + Util.printTree(treeNode); + } + + /** + * 解题思路: + * 分:几种情况 + * 1、根节点和左子树的某个数字交换 -> 由于根节点大于左子树中的所有数,所以交换后我们只要找左子树中最大的那个数,就是所交换的那个数 + * 2、根节点和右子树的某个数字交换 -> 由于根节点小于右子树中的所有数,所以交换后我们只要在右子树中最小的那个数,就是所交换的那个数 + * 3、左子树和右子树的两个数字交换 -> 找左子树中最大的数,右子树中最小的数,即对应两个交换的数 + * 4、左子树中的两个数字交换 + * 5、右子树中的两个数字交换 + * @param root + */ + public void recoverTree(TreeNode root) { + if (root == null) { + return; + } + //寻找左子树中最大的节点 + TreeNode maxLeft = getMaxOfBST(root.left); + //寻找右子树中最小的节点 + TreeNode minRight = getMinOfBST(root.right); + + if (minRight != null && maxLeft != null) { + //左边的大于根节点,右边的小于根节点,对应情况 3,左右子树中的两个数字交换 + if ( maxLeft.val > root.val && minRight.val < root.val) { + int temp = minRight.val; + minRight.val = maxLeft.val; + maxLeft.val = temp; + } + } + + if (maxLeft != null) { + //左边最大的大于根节点,对应情况 1,根节点和左子树的某个数做了交换 + if (maxLeft.val > root.val) { + int temp = maxLeft.val; + maxLeft.val = root.val; + root.val = temp; + } + } + + if (minRight != null) { + //右边最小的小于根节点,对应情况 2,根节点和右子树的某个数做了交换 + if (minRight.val < root.val) { + int temp = minRight.val; + minRight.val = root.val; + root.val = temp; + } + } + //对应情况 4,左子树中的两个数进行了交换 + recoverTree(root.left); + //对应情况 5,右子树中的两个数进行了交换 + recoverTree(root.right); + + } + //寻找树中最小的节点 + private TreeNode getMinOfBST(TreeNode root) { + if (root == null) { + return null; + } + TreeNode minLeft = getMinOfBST(root.left); + TreeNode minRight = getMinOfBST(root.right); + TreeNode min = root; + if (minLeft != null && min.val > minLeft.val) { + min = minLeft; + } + if (minRight != null && min.val > minRight.val) { + min = minRight; + } + return min; + } + + //寻找树中最大的节点 + private TreeNode getMaxOfBST(TreeNode root) { + if (root == null) { + return null; + } + TreeNode maxLeft = getMaxOfBST(root.left); + TreeNode maxRight = getMaxOfBST(root.right); + TreeNode max = root; + if (maxLeft != null && max.val < maxLeft.val) { + max = maxLeft; + } + if (maxRight != null && max.val < maxRight.val) { + max = maxRight; + } + return max; + } + +} diff --git a/src/pp/arithmetic/model/Node.java b/src/pp/arithmetic/model/Node.java new file mode 100644 index 0000000..15ac2de --- /dev/null +++ b/src/pp/arithmetic/model/Node.java @@ -0,0 +1,24 @@ +package pp.arithmetic.model; + +/** + * Created by wangpeng on 2019-12-14. + */ +public class Node { + public int val; + public Node left; + public Node right; + public Node next; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, Node _left, Node _right, Node _next) { + val = _val; + left = _left; + right = _right; + next = _next; + } +} diff --git a/src/pp/arithmetic/offer/_03_findRepeatNumber.java b/src/pp/arithmetic/offer/_03_findRepeatNumber.java new file mode 100644 index 0000000..8fbedfa --- /dev/null +++ b/src/pp/arithmetic/offer/_03_findRepeatNumber.java @@ -0,0 +1,124 @@ +package pp.arithmetic.offer; + +import java.util.HashMap; + +/** + * Created by wangpeng on 2020-07-28. + * 剑指 Offer 03. 数组中重复的数字 + *

+ * 找出数组中重复的数字。 + *

+ *

+ * 在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。 + *

+ * 示例 1: + *

+ * 输入: + * [2, 3, 1, 0, 2, 5, 3] + * 输出:2 或 3 + *   + *

+ * 限制: + *

+ * 2 <= n <= 100000 + *

+ * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _03_findRepeatNumber { + + public static void main(String[] args) { + _03_findRepeatNumber findRepeatNumber = new _03_findRepeatNumber(); + int repeatNumber = findRepeatNumber.findRepeatNumber(new int[]{2, 3, 0, 1, 2, 3, 4, 5, 3}); + System.out.println(repeatNumber); + int repeatNumber2 = findRepeatNumber.findRepeatNumber2(new int[]{2, 3, 0, 1, 2, 3, 4, 5, 3}); + System.out.println(repeatNumber2); + int repeatNumber3 = findRepeatNumber.findRepeatNumber3(new int[]{2, 3, 0, 1, 2, 3, 4, 5, 3}); + System.out.println(repeatNumber3); + } + + /** + * 解题思路: + * 方案一:最直接的方式,使用一个HashMap进行存储遍历过的数字,性能肯定不会差,内存占用会高 + *

+ * 执行用时:13 ms, 在所有 Java 提交中击败了8.98%的用户 + * 内存消耗:48.7 MB, 在所有 Java 提交中击败了100.00%的用户 + *

+ * 执行结果有点出人意料,用时偏高 + *

+ * 优化方案二:{@link _03_findRepeatNumber#findRepeatNumber2(int[])} + * + * @param nums + * @return + */ + public int findRepeatNumber(int[] nums) { + HashMap map = new HashMap<>(); + for (int i = 0; i < nums.length; i++) { + int num = nums[i]; + if (map.getOrDefault(num, false)) { + return num; + } + map.put(num, true); + } + + return 0; + } + + /** + * 针对方案一的提交结果,看看哪些地方可以优化 + * 分析可能是HashMao扩容导致的耗时,用同等大小的数组,保存出现次数 + * + * 执行用时:2 ms, 在所有 Java 提交中击败了70.22%的用户 + * 内存消耗:46.9 MB, 在所有 Java 提交中击败了100.00%的用户 + * + * 结果满足要求,印证了HashMap扩容存在耗时 + * + * 最后参考一个最优方案,不需要额外储存空间:{@link _03_findRepeatNumber#findRepeatNumber3(int[])} + * + * @param nums + * @return + */ + public int findRepeatNumber2(int[] nums) { + int[] numCounts = new int[nums.length]; + for (int i = 0; i < nums.length; i++) { + int num = nums[i]; + if (numCounts[num] != 0) { + return num; + } + numCounts[num]++; + } + + return 0; + } + + /** + * 方案三: + * 利用数组本身去存储遍历过程的结果,数组第i位就是i,如果后面的有相应的i,则存在重复元素 + * 此方案前提条件:" 在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内 ",不然数组可能会越界 + * 此方案还有个劣势:修改了原数组 + * + * 执行用时:1 ms, 在所有 Java 提交中击败了91.54%的用户 + * 内存消耗:47.9 MB, 在所有 Java 提交中击败了100.00%的用户 + * @param nums + * @return + */ + public int findRepeatNumber3(int[] nums) { + int i = 0; + while(i < nums.length){ + if(i != nums[i]){ + int tmp = nums[nums[i]]; + if(tmp == nums[i]){ + return tmp; + } + nums[nums[i]] = nums[i]; + nums[i] = tmp; + }else{ + i++; + } + } + + return -1; + + } +} diff --git a/src/pp/arithmetic/offer/_04_findNumberIn2DArray.java b/src/pp/arithmetic/offer/_04_findNumberIn2DArray.java new file mode 100644 index 0000000..d33ab90 --- /dev/null +++ b/src/pp/arithmetic/offer/_04_findNumberIn2DArray.java @@ -0,0 +1,135 @@ +package pp.arithmetic.offer; + +/** + * Created by wangpeng on 2020-07-29. + * 剑指 Offer 04. 二维数组中的查找 + * + * 在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。 + * + *   + * + * 示例: + * + * 现有矩阵 matrix 如下: + * + * [ + * [1, 4, 7, 11, 15], + * [2, 5, 8, 12, 19], + * [3, 6, 9, 16, 22], + * [10, 13, 14, 17, 24], + * [18, 21, 23, 26, 30] + * ] + * 给定 target = 5,返回 true。 + * + * 给定 target = 20,返回 false。 + * + *   + * + * 限制: + * + * 0 <= n <= 1000 + * + * 0 <= m <= 1000 + * + *   + * + * 注意:本题与主站 240 题相同:https://leetcode-cn.com/problems/search-a-2d-matrix-ii/ + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _04_findNumberIn2DArray { + + public static void main(String[] args) { + _04_findNumberIn2DArray findNumberIn2DArray = new _04_findNumberIn2DArray(); + int[][] matrix = { + {1,2,3,4,5}, + {6,7,8,9,10}, + {11,12,13,14,15}, + {16,17,18,19,20}, + {21,22,23,24,25} + }; + System.out.println(findNumberIn2DArray.findNumberIn2DArray(matrix,5)); + System.out.println(findNumberIn2DArray.findNumberIn2DArray(matrix,20)); + } + + /** + * 解题思路:一眼看过去,在一个有序的规则里找一个数,第一时间想到的是二分查找,看看能不能找到二分查找的规律,从实例中看 + * + * 1.n*m的数组中,[0,0]=1肯定最小,[n-1,m-1]=30肯定最大,如果target<[0,0] || target>[n-1,m-1]肯定不存在,返回false + * 2.如果target=[0,0] || target=[n-1,m-1],直接返回true + * 3.如果数组大小2*2,则直接返回结果 + * 4.找到数组的中位数[n/2,m/2] = 9 + * 5.target=[n/2,m/2],则直接找到结果,返回true + * 6.target<[n/2,m/2],则可能存在的区域是[0,0]-[n-1,m/2-1]或者[0,m/2]-[n/2-1,m-1]之间(也就是说除了右下角的两块区域),递归 + * 7.target>[n/2,m/2],则可能存在的区域是[n/2+1,0]-[n-1,m-1]或者[0,m/2+1]-[n/2,m-1](也就是说除了左上角的两块区域),递归 + * + * 方法二:利用自身数组的规律求解,详见:{@link _04_findNumberIn2DArray#findNumberIn2DArray2(int[][], int)} + * + * @param matrix + * @param target + * @return + */ + public boolean findNumberIn2DArray(int[][] matrix, int target) { + if (matrix.length == 0) return false; + int n = matrix.length; + int m = matrix[0].length; + return dfs(matrix, target, 0, 0, n - 1, m - 1); + } + + private boolean dfs(int[][] matrix, int target, int sx, int sy, int ex, int ey) { + if (!checkXY(matrix, sx, sy,ex,ey)) return false; + int start = matrix[sx][sy]; + int end = matrix[ex][ey]; + if (target < start || target > end) return false; + int mx = (ex + sx) / 2; + int my = (ey + sy) / 2; + int mid = matrix[mx][my]; + if (target < mid) { + return dfs(matrix, target, sx, sy, ex, my-1) || dfs(matrix, target, sx, my, mx-1, ey) ; + } + if (target > mid) { + return dfs(matrix, target, mx + 1, sy, ex, ey) || dfs(matrix, target, sx, my + 1, mx, ey); + } + return true; + } + + //检查输入参数是否有效 + private boolean checkXY(int[][] matrix, int sx, int sy, int ex, int ey) { + if (sx < 0 || sx > matrix.length - 1) return false; + if (sy < 0 || sy > matrix[0].length - 1) return false; + if (ex < 0 || ex > matrix.length - 1) return false; + if (ey < 0 || ey > matrix[0].length - 1) return false; + if (sx > ex || sy > ey) return false; + return true; + } + + /** + * 方法二:找到数组的右上角,此位置正下方都比他大,正左方都比他小,左下角区域可大可小,以此为起始锚点 + * 1.target>锚点,锚点位置向下移动一行 + * 2.target<锚点,锚点位置向左移动一列 + * 3.target=锚点,返回结果true + * 4.锚点移除列表边线,返回结果false + * @param matrix + * @param target + * @return + */ + public boolean findNumberIn2DArray2(int[][] matrix, int target) { + if (matrix == null || matrix.length == 0) return false; + //选取右上角 + int row = 0; + int col = matrix[0].length - 1; + while (row < matrix.length && col >= 0) { + if (matrix[row][col] == target) { + return true; + } else if (matrix[row][col] > target) { + col--; + } else if (matrix[row][col] < target) { + row++; + } + } + return false; + } + +} diff --git a/src/pp/arithmetic/offer/_05_replaceSpace.java b/src/pp/arithmetic/offer/_05_replaceSpace.java new file mode 100644 index 0000000..8acd6d5 --- /dev/null +++ b/src/pp/arithmetic/offer/_05_replaceSpace.java @@ -0,0 +1,53 @@ +package pp.arithmetic.offer; + +/** + * Created by wangpeng on 2020-07-30. + * 剑指 Offer 05. 替换空格 + * + * 请实现一个函数,把字符串 s 中的每个空格替换成"%20"。 + * + *   + * + * 示例 1: + * + * 输入:s = "We are happy." + * 输出:"We%20are%20happy." + *   + * + * 限制: + * + * 0 <= s 的长度 <= 10000 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _05_replaceSpace { + + public static void main(String[] args) { + _05_replaceSpace replaceSpace = new _05_replaceSpace(); + System.out.println(replaceSpace.replaceSpace("We are happy.")); + } + + /** + * 解题思路: + * 看到题目最直接的想法就是遍历异常,遇到空格就替换 + * 没有清楚这道题到底想考什么? + * @param s + * @return + */ + public String replaceSpace(String s) { + char[] chars = s.toCharArray(); + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < chars.length; i++) { + char aChar = chars[i]; + if (aChar == ' '){ + builder.append("%20"); + }else{ + builder.append(aChar); + } + } + + return builder.toString(); + } +} diff --git a/src/pp/arithmetic/offer/_06_reversePrint.java b/src/pp/arithmetic/offer/_06_reversePrint.java new file mode 100644 index 0000000..50ea158 --- /dev/null +++ b/src/pp/arithmetic/offer/_06_reversePrint.java @@ -0,0 +1,64 @@ +package pp.arithmetic.offer; + +import pp.arithmetic.Util; +import pp.arithmetic.model.ListNode; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by wangpeng on 2020-07-30. + * 剑指 Offer 06. 从尾到头打印链表 + * + * 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。 + * + *   + * + * 示例 1: + * + * 输入:head = [1,3,2] + * 输出:[2,3,1] + *   + * + * 限制: + * + * 0 <= 链表长度 <= 10000 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _06_reversePrint { + + public static void main(String[] args) { + ListNode listNode = Util.generateListNodeBySize(10); + Util.printListNode(listNode); + _06_reversePrint reversePrint = new _06_reversePrint(); + int[] arr = reversePrint.reversePrint(listNode); + Util.printArray(arr); + } + + /** + * 解题思路: + * 链表的问题,最直接也只能是遍历+递归,可以借助多指针一起,此题只需要遍历就可以了 + * @param head + * @return + */ + public int[] reversePrint(ListNode head) { + List list = new ArrayList<>(); + dfs(head,list); + int[] retArr = new int[list.size()]; + for (int i = 0; i < list.size(); i++) { + retArr[i] = list.get(i); + } + return retArr; + } + + private void dfs(ListNode node,List list){ + if (node == null){ + return; + } + dfs(node.next,list); + list.add(node.val); + } +} diff --git a/src/pp/arithmetic/offer/_07_buildTree.java b/src/pp/arithmetic/offer/_07_buildTree.java new file mode 100644 index 0000000..6c03b4c --- /dev/null +++ b/src/pp/arithmetic/offer/_07_buildTree.java @@ -0,0 +1,103 @@ +package pp.arithmetic.offer; + +import pp.arithmetic.Util; +import pp.arithmetic.model.TreeNode; + +/** + * Created by wangpeng on 2020-08-04. + * + * 剑指 Offer 07. 重建二叉树 + * + * 输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。 + * + *   + * + * 例如,给出 + * + * 前序遍历 preorder = [3,9,20,15,7] + * 中序遍历 inorder = [9,3,15,20,7] + * 返回如下的二叉树: + * + * 3 + * / \ + * 9 20 + * / \ + * 15 7 + *   + * + * 限制: + * + * 0 <= 节点个数 <= 5000 + * + *   + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _07_buildTree { + + public static void main(String[] args) { + _07_buildTree buildTree = new _07_buildTree(); + int[] preorder = {3, 9, 20, 15, 7}; + int[] inorder = {9,3,15,20,7}; + TreeNode treeNode = buildTree.buildTree(preorder, inorder); + Util.printTree(treeNode); + } + + /** + * 解题思路: + * 1、知道前序遍历,首位就是根节点 + * 2、由于不存在重复数字,根据根节点找到中序遍历的位置I,I前就是左子树的中序,I后就是右子树的中序 + * 3、在前序数组中,根据左右子树中序的长度,能找到左右子树对应的前序遍历数组 + * 4、循环1-3,得到左右子树的对应的前序&中序数组,最终得到构建的树 + * + * 优化建议:得到左右子树对应的数组的时候,有两种方案: + * 一、拷贝新数组 + * 二、原数组上理由index指针获取结果(性能和效率都更高) + * + * 本题解基于方案二 + * + * @param preorder + * @param inorder + * @return + */ + public TreeNode buildTree(int[] preorder, int[] inorder) { + if (preorder.length == 0) return null; + return dfs(preorder.length,preorder,0,inorder,0); + } + + // 从前序和中序构造二叉树,前序和中序是大数组中的一段[start, start + count) + private TreeNode dfs(int count, int[] preOrder, int preStart, int[] inOrder, int inStart) { + if (count <= 0) return null; + + int rootValue = preOrder[preStart]; + TreeNode root = new TreeNode(rootValue); + + // 从inorder中找到root值,(inorder)左边就是左子树,(inorder)右边就是右子树 + // 然后在preorder中,数出与inorder中相同的个数即可 + int pos = inStart + count - 1; + for (; pos >= inStart; --pos) { + if (inOrder[pos] == rootValue) { + break; + } + } + int leftCount = pos - inStart; + int rightCount = inStart + count - pos - 1; + + if (leftCount > 0) { + int leftInStart = inStart; + int leftPreStart = preStart + 1; + root.left = dfs(leftCount, preOrder, leftPreStart, inOrder, leftInStart); + } + + if (rightCount > 0) { + int rightInStart = pos + 1; + int rightPreStart = preStart + 1 + leftCount; + root.right = dfs(rightCount, preOrder, rightPreStart, inOrder, rightInStart); + } + + return root; + } + +} diff --git a/src/pp/arithmetic/offer/_09_CQueue.java b/src/pp/arithmetic/offer/_09_CQueue.java new file mode 100644 index 0000000..b8406a3 --- /dev/null +++ b/src/pp/arithmetic/offer/_09_CQueue.java @@ -0,0 +1,118 @@ +package pp.arithmetic.offer; + +import java.util.Stack; + +/** + * Created by wangpeng on 2020-08-04. + * + * 剑指 Offer 09. 用两个栈实现队列 + * + * 用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 ) + * + *   + * + * 示例 1: + * + * 输入: + * ["CQueue","appendTail","deleteHead","deleteHead"] + * [[],[3],[],[]] + * 输出:[null,null,3,-1] + * 示例 2: + * + * 输入: + * ["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"] + * [[],[],[5],[2],[],[]] + * 输出:[null,-1,null,null,5,2] + * 提示: + * + * 1 <= values <= 10000 + * 最多会对 appendTail、deleteHead 进行 10000 次调用 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _09_CQueue { + + public static void main(String[] args) { + CQueue cQueue = new CQueue(); + System.out.println(cQueue.deleteHead()); + cQueue.appendTail(5); + cQueue.appendTail(2); + System.out.println(cQueue.deleteHead()); + System.out.println(cQueue.deleteHead()); + } + + /** + * 解题思路: + * 一个栈用于储存,另一个用于删除时候暂存数据 + * + * 提交结果: + * 执行用时:416 ms, 在所有 Java 提交中击败了5.06%的用户 + * 内存消耗:48.5 MB, 在所有 Java 提交中击败了32.71%的用户 + * + * delete操作存在十分频繁的数据移动操作,待优化{@link CQueue2} + */ + static class CQueue { + + Stack add; + Stack stash; + + public CQueue() { + add = new Stack(); + stash = new Stack(); + } + + public void appendTail(int value) { + add.push(value); + } + + public int deleteHead() { + int retVal = -1; + while (!add.isEmpty()){ + retVal = add.pop(); + stash.push(retVal); + } + //将删除的val剔除掉 + if (!stash.isEmpty()) { + stash.pop(); + } + while (!stash.isEmpty()){ + add.push(stash.pop()); + } + + return retVal; + } + } + + /** + * 优化思路: + * 1.stash用来delete操作,当stash为空的时候,才将add中的数据同步过去 + */ + static class CQueue2 { + + Stack add; + Stack stash; + + public CQueue2() { + add = new Stack(); + stash = new Stack(); + } + + public void appendTail(int value) { + add.push(value); + } + + public int deleteHead() { + if (stash.isEmpty()){ + if (add.isEmpty()) return -1; + while (!add.isEmpty()){ + stash.push(add.pop()); + } + return stash.pop(); + }else{ + return stash.pop(); + } + } + } +} diff --git a/src/pp/arithmetic/offer/_10_2_numWays.java b/src/pp/arithmetic/offer/_10_2_numWays.java new file mode 100644 index 0000000..f3cf657 --- /dev/null +++ b/src/pp/arithmetic/offer/_10_2_numWays.java @@ -0,0 +1,65 @@ +package pp.arithmetic.offer; + +/** + * Created by wangpeng on 2020-08-05. + * + * 剑指 Offer 10- II. 青蛙跳台阶问题 + * + * + * 一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。 + * + * 答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。 + * + * 示例 1: + * + * 输入:n = 2 + * 输出:2 + * 示例 2: + * + * 输入:n = 7 + * 输出:21 + * 示例 3: + * + * 输入:n = 0 + * 输出:1 + * 提示: + * + * 0 <= n <= 100 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/qing-wa-tiao-tai-jie-wen-ti-lcof + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _10_2_numWays { + + public static void main(String[] args) { + _10_2_numWays numWays = new _10_2_numWays(); + System.out.println(numWays.numWays(2)); + System.out.println(numWays.numWays(3)); + System.out.println(numWays.numWays(4)); + System.out.println(numWays.numWays(5)); + System.out.println(numWays.numWays(6)); + System.out.println(numWays.numWays(40)); + } + + /** + * 解题思路:借鉴动态规划思路 + * 1.dp[0]=1,dp[1]=1,d[2]=dp[0]+d[1] + * 2.dp[n]=dp[n-1]+dp[n-2] + * + * @param n + * @return + */ + public int numWays(int n) { + if (n == 0) return 1; + if (n == 1) return 1; + int[] dp = new int[n+1]; + dp[0] = 1; + dp[1] = 1; + for (int i = 2; i <= n; i++) { + dp[i] = (dp[i-1]+dp[i-2])%1000000007; + } + + return dp[n]; + } +} diff --git a/src/pp/arithmetic/offer/_10_fib.java b/src/pp/arithmetic/offer/_10_fib.java new file mode 100644 index 0000000..406f9b0 --- /dev/null +++ b/src/pp/arithmetic/offer/_10_fib.java @@ -0,0 +1,65 @@ +package pp.arithmetic.offer; + +/** + * Created by wangpeng on 2020-08-04. + * + * 剑指 Offer 10- I. 斐波那契数列 + * + * 写一个函数,输入 n ,求斐波那契(Fibonacci)数列的第 n 项。斐波那契数列的定义如下: + * + * F(0) = 0,   F(1) = 1 + * F(N) = F(N - 1) + F(N - 2), 其中 N > 1. + * 斐波那契数列由 0 和 1 开始,之后的斐波那契数就是由之前的两数相加而得出。 + * + * 答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。 + * + *   + * + * 示例 1: + * + * 输入:n = 2 + * 输出:1 + * 示例 2: + * + * 输入:n = 5 + * 输出:5 + *   + * + * 提示: + * + * 0 <= n <= 100 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/fei-bo-na-qi-shu-lie-lcof + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _10_fib { + + public static void main(String[] args) { + _10_fib fib = new _10_fib(); + System.out.println(fib.fib(2)); + System.out.println(fib.fib(5)); + System.out.println(fib.fib(100)); + } + + /** + * 解题思路: + * 有两个方案: + * 一、是从n开始递归求解f(n)=f(n-1)+f(n-2),这种递归效率较低,当n比较大时候存在大量重复的计算 + * 二、从0开始计算,存储下每次计算的结果,逐步计算到n,借助动态规划 + * + * @param n + * @return + */ + public int fib(int n) { + if (n == 0) return 0; + if (n == 1) return 1; + int[] dp = new int[n+1]; + dp[0] = 0; + dp[1] = 1; + for (int i = 2; i <= n; i++) { + dp[i] = (dp[i-1]+dp[i-2])%1000000007; + } + return dp[n]; + } +} diff --git a/src/pp/arithmetic/offer/_11_minArray.java b/src/pp/arithmetic/offer/_11_minArray.java new file mode 100644 index 0000000..b0795f6 --- /dev/null +++ b/src/pp/arithmetic/offer/_11_minArray.java @@ -0,0 +1,52 @@ +package pp.arithmetic.offer; + +/** + * Created by wangpeng on 2020-08-05. + * + * + * 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。   + * + * 示例 1: + * + * 输入:[3,4,5,1,2] + * 输出:1 + * 示例 2: + * + * 输入:[2,2,2,0,1] + * 输出:0 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _11_minArray { + + public static void main(String[] args) { + _11_minArray minArray = new _11_minArray(); + System.out.println(minArray.minArray(new int[]{3,4,5,1,2})); + System.out.println(minArray.minArray(new int[]{2,2,2,0,1})); + } + + /** + * 解题思路: + * 递增数组经过一次旋转,从递增到递减的转折点,则是最小的 + * @param numbers + * @return + */ + public int minArray(int[] numbers) { + if (numbers == null || numbers.length == 0) return 0; + int retVal = numbers[0]; + int preVal = numbers[0]; + for (int i = 1; i < numbers.length; i++) { + int number = numbers[i]; + if (number >= preVal){ + preVal = number; + }else{ + retVal = number; + break; + } + } + + return retVal; + } +} diff --git a/src/pp/arithmetic/offer/_12_exist.java b/src/pp/arithmetic/offer/_12_exist.java new file mode 100644 index 0000000..503e369 --- /dev/null +++ b/src/pp/arithmetic/offer/_12_exist.java @@ -0,0 +1,105 @@ +package pp.arithmetic.offer; + +/** + * Created by wangpeng on 2020-08-05. + *

+ * 剑指 Offer 12. 矩阵中的路径 + *

+ * 请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。 + * 如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。例如,在下面的3×4的矩阵中包含一条字符串“bfce”的路径(路径中的字母用加粗标出)。 + *

+ * [["a","b","c","e"], + * ["s","f","c","s"], + * ["a","d","e","e"]] + *

+ * 但矩阵中不包含字符串“abfb”的路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入这个格子。 + *

+ *   + *

+ * 示例 1: + *

+ * 输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" + * 输出:true + * 示例 2: + *

+ * 输入:board = [["a","b"],["c","d"]], word = "abcd" + * 输出:false + * 提示: + *

+ * 1 <= board.length <= 200 + * 1 <= board[i].length <= 200 + *

+ * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _12_exist { + + public static void main(String[] args) { + _12_exist exist = new _12_exist(); +// char[][] board = new char[][]{ +// {'A', 'B', 'C', 'E'}, +// {'S', 'F', 'C', 'S'}, +// {'A', 'D', 'E', 'E'} +// }; +// System.out.println(exist.exist(board,"ABFACED")); +// System.out.println(exist.exist(new char[][]{ +// {'a','b'}, +// {'c','d'} +// },"abcd")); + System.out.println(exist.exist(new char[][]{ + {'C','A','A'}, + {'A','A','A'}, + {'B','C','D'} + },"AAB")); + } + + /** + * 解题思路: + * 从board的[0,0]开始向上、左、下、右进行深度遍历,逐步去匹配word中的字符,新建个history保存遍历路径,防止死循环 + * + * @param board + * @param word + * @return + */ + public boolean exist(char[][] board, String word) { + if (board == null || board.length == 0) return false; + int[][] history = new int[board.length][board[0].length]; + return dfs(board, word, history, 0, 0, 0); + } + + private boolean dfs(char[][] board, String word, int[][] history, int wi, int nx, int ny) { + if (wi >= word.length()) { + //word遍历结束才返回true + return true; + } + //遍历越界 + if (nx < 0 || nx >= board.length || ny < 0 || ny >= board[nx].length) return false; + //之前走过这个位置 + if (history[nx][ny] == 1) return false; + if (board[nx][ny] == word.charAt(wi)) { + history[nx][ny] = 1; + if (dfs(board, word, history, wi + 1, nx, ny + 1) + || dfs(board, word, history, wi + 1, nx + 1, ny) + || dfs(board, word, history, wi + 1, nx, ny - 1) + || dfs(board, word, history, wi + 1, nx - 1, ny)) { + return true; + } + history[nx][ny] = 0; + } + if (wi == 0) { + //定位首个字符的标识位 + if (nx < board.length - 1) { + if (dfs(board, word, history, wi, nx + 1, ny)) { + return true; + } + } else if (ny < board[0].length - 1) { + if (dfs(board, word, history, wi, 0, ny + 1)) { + return true; + } + } + } + return false; + } + +} diff --git a/src/pp/arithmetic/offer/_13_movingCount.java b/src/pp/arithmetic/offer/_13_movingCount.java new file mode 100644 index 0000000..e89db86 --- /dev/null +++ b/src/pp/arithmetic/offer/_13_movingCount.java @@ -0,0 +1,83 @@ +package pp.arithmetic.offer; + +/** + * Created by wangpeng on 2020-08-06. + *

+ * 剑指 Offer 13. 机器人的运动范围 + *

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

+ *   + *

+ * 示例 1: + *

+ * 输入:m = 2, n = 3, k = 1 + * 输出:3 + * 示例 2: + *

+ * 输入:m = 3, n = 1, k = 0 + * 输出:1 + * 提示: + *

+ * 1 <= n,m <= 100 + * 0 <= k <= 20 + *

+ * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _13_movingCount { + + public static void main(String[] args) { + _13_movingCount movingCount = new _13_movingCount(); + System.out.println(movingCount.movingCount(2,3,1)); + System.out.println(movingCount.movingCount(3,1,0)); + System.out.println(movingCount.movingCount(1,2,1)); + System.out.println(movingCount.movingCount(10,10,2)); + System.out.println(movingCount.movingCount(16,8,4)); + } + + private int retVal = 0; + + /** + * 解题思路: + * 使用int[m][n]大小的数组保存行进记录,上下左右进行DFS,不满足条件的跳过 + * 需要注意的可能中间某些行和列相加也满足条件,所以需要整个行和列都需要遍历完(不需要考虑,题中是从0,0开始的) + * + * @param m + * @param n + * @param k + * @return + */ + public int movingCount(int m, int n, int k) { + if (k < 0 || m <=0 || n<=0) return 0; + retVal = 0; + int[][] history = new int[m][n]; + dfs(0,0,m,n,k,history); + return retVal; + } + + private void dfs(int cx, int cy, int m, int n, int k, int[][] history) { + if (cx < 0 || cx >= m || cy < 0 || cy >= n) return; + if (add(cx, cy) > k) return; + if (history[cx][cy] == 1) return; + history[cx][cy] = 1; + retVal++; + dfs(cx, cy + 1, m, n, k, history); + dfs(cx + 1, cy, m, n, k, history); + dfs(cx, cy - 1, m, n, k, history); + dfs(cx - 1, cy, m, n, k, history); + } + + private int add(int x, int y) { + int retVal = 0; + retVal += x / 100; + retVal += (x - x / 100 * 100) / 10; + retVal += x - x / 100 * 100 - (x - x / 100 * 100) / 10 * 10; + retVal += y / 100; + retVal += (y - y / 100 * 100) / 10; + retVal += y - y / 100 * 100 - (y - y / 100 * 100) / 10 * 10; + return retVal; + } +} diff --git a/src/pp/arithmetic/offer/_14_1_cuttingRope.java b/src/pp/arithmetic/offer/_14_1_cuttingRope.java new file mode 100644 index 0000000..939abcc --- /dev/null +++ b/src/pp/arithmetic/offer/_14_1_cuttingRope.java @@ -0,0 +1,68 @@ +package pp.arithmetic.offer; + +/** + * Created by wangpeng on 2020-08-07. + * + * 剑指 Offer 14- I. 剪绳子 + * + * 给你一根长度为 n 的绳子,请把绳子剪成整数长度的 m 段(m、n都是整数,n>1并且m>1),每段绳子的长度记为 k[0],k[1]...k[m-1] 。请问 k[0]*k[1]*...*k[m-1] 可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。 + * + * 示例 1: + * + * 输入: 2 + * 输出: 1 + * 解释: 2 = 1 + 1, 1 × 1 = 1 + * 示例 2: + * + * 输入: 10 + * 输出: 36 + * 解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36 + * 提示: + * + * 2 <= n <= 58 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/jian-sheng-zi-lcof + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _14_1_cuttingRope { + + public static void main(String[] args) { + _14_1_cuttingRope cuttingRope = new _14_1_cuttingRope(); + System.out.println(cuttingRope.cuttingRope(8)); + System.out.println(cuttingRope.cuttingRope(10)); + System.out.println(cuttingRope.cuttingRope(14)); + System.out.println(cuttingRope.cuttingRope(58)); + } + + /** + * 解题思路: + * 手动模拟了从2-10的最大乘积数字拆解,发现了一个现象: + * 对于数字n,n一直除以2到1为止,得到的数字就是最大的乘积,举例如下: + * 数字n 2 3 4 5 6 7 8 9 10 + * 乘积 1,1 1,2 2,2 2,3 3,3 3,4(2,2) 4(2,2),4(2,2) 4,5(2,3) 5(2,3),5(2,3) + * 发现到了后面的最大乘积可以利用之前的计算好的结果,从而得出动态规划转移方程 + * dp[i]=dp[i/2]*dp[i-i/2](i>3) + * 上面有问题,例如8的最大值不是除以2得到4*4=16,而是3*2*3=18,所以得双重循环取所有情况的最大值 + * for (int j = 1; j <= i / 2; j++) { + * dp[i] = Math.max(dp[i], dp[j] * dp[i - j]); + * } + * + * @param n + * @return + */ + public int cuttingRope(int n) { + if (n <= 3) return n - 1; + int[] dp = new int[n + 1]; + //初始化,1,2,3特殊处理 + dp[1] = 1; + dp[2] = 2; + dp[3] = 3; + for (int i = 4; i <= n; i++) { + for (int j = 1; j <= i / 2; j++) { + dp[i] = Math.max(dp[i], dp[j] * dp[i - j]); + } + } + return dp[n]; + } +} diff --git a/src/pp/arithmetic/offer/_15_hammingWeight.java b/src/pp/arithmetic/offer/_15_hammingWeight.java new file mode 100644 index 0000000..bfae0b4 --- /dev/null +++ b/src/pp/arithmetic/offer/_15_hammingWeight.java @@ -0,0 +1,57 @@ +package pp.arithmetic.offer; + +/** + * Created by wangpeng on 2020-08-10. + * 剑指 Offer 15. 二进制中1的个数 + * + * 请实现一个函数,输入一个整数,输出该数二进制表示中 1 的个数。例如,把 9 表示成二进制是 1001,有 2 位是 1。因此,如果输入 9,则该函数输出 2。 + * + * 示例 1: + * + * 输入:00000000000000000000000000001011 + * 输出:3 + * 解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。 + * 示例 2: + * + * 输入:00000000000000000000000010000000 + * 输出:1 + * 解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。 + * 示例 3: + * + * 输入:11111111111111111111111111111101 + * 输出:31 + * 解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 '1'。 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _15_hammingWeight { + + public static void main(String[] args) { + _15_hammingWeight hammingWeight = new _15_hammingWeight(); + System.out.println(hammingWeight.hammingWeight(11)); + System.out.println(hammingWeight.hammingWeight(128)); +// System.out.println(hammingWeight.hammingWeight(4294967293)); + } + + + /** + * 解题思路: + * 如果n%2!=0,则1的个数+1,直到n=1 + * + * 注意无符号的,对应int会超 右移动使用>>>(无符号右移) + * @param n + * @return + */ + // you need to treat n as an unsigned value + public int hammingWeight(int n) { + int retVal = 0; + while (n != 0) { + retVal += n & 1; + n = n >>> 1; + } + + return retVal; + } +} diff --git a/src/pp/arithmetic/offer/_16_myPow.java b/src/pp/arithmetic/offer/_16_myPow.java new file mode 100644 index 0000000..0a49745 --- /dev/null +++ b/src/pp/arithmetic/offer/_16_myPow.java @@ -0,0 +1,71 @@ +package pp.arithmetic.offer; + +/** + * Created by wangpeng on 2020-08-11. + * + * 剑指 Offer 16. 数值的整数次方 + * + * 实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。 + * + *   + * + * 示例 1: + * + * 输入: 2.00000, 10 + * 输出: 1024.00000 + * 示例 2: + * + * 输入: 2.10000, 3 + * 输出: 9.26100 + * 示例 3: + * + * 输入: 2.00000, -2 + * 输出: 0.25000 + * 解释: 2-2 = 1/22 = 1/4 = 0.25 + *   + * + * 说明: + * + * -100.0 < x < 100.0 + * n 是 32 位有符号整数,其数值范围是 [−2^31, 2^31 − 1] 。 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _16_myPow { + + public static void main(String[] args) { + _16_myPow myPow = new _16_myPow(); + System.out.println(myPow.myPow(2.0,10)); + System.out.println(myPow.myPow(2.1,3)); + System.out.println(myPow.myPow(2.0,-2)); + System.out.println(myPow.myPow(0.00001, 2147483647)); + System.out.println(myPow.myPow(2, -2147483648)); + } + + /** + * 解题思路: + * 最简单的方式就是直接循环0-n,将x相乘得出结果,题目中的n范围比较大,这样子效率太低 + * 优化:类似2分拆分,一半一半的计算结果,最终相乘 + * @param x + * @param n + * @return + */ + public double myPow(double x, int n) { + if (n == 0) return 1; + if (n<0){ + //指数是否负数,负数需要取倒数 + x = 1/x; + } + //是否取一半还有剩余一个 + boolean isOdd = n % 2 != 0; + double v = myPow(x, Math.abs(n / 2)); + if (isOdd) { + return v * v * x; + } else { + return v * v; + } + } + +} diff --git a/src/pp/arithmetic/offer/_17_printNumbers.java b/src/pp/arithmetic/offer/_17_printNumbers.java new file mode 100644 index 0000000..6eb52a1 --- /dev/null +++ b/src/pp/arithmetic/offer/_17_printNumbers.java @@ -0,0 +1,56 @@ +package pp.arithmetic.offer; + +import pp.arithmetic.Util; + +/** + * Created by wangpeng on 2020-08-11. + * + * 剑指 Offer 17. 打印从1到最大的n位数 + * + * 输入数字 n,按顺序打印出从 1 到最大的 n 位十进制数。比如输入 3,则打印出 1、2、3 一直到最大的 3 位数 999。 + * + * 示例 1: + * + * 输入: n = 1 + * 输出: [1,2,3,4,5,6,7,8,9] + *   + * + * 说明: + * + * 用返回一个整数列表来代替打印 + * n 为正整数 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/da-yin-cong-1dao-zui-da-de-nwei-shu-lcof + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _17_printNumbers { + + public static void main(String[] args) { + _17_printNumbers printNumbers = new _17_printNumbers(); + Util.printArray(printNumbers.printNumbers(1)); + Util.printArray(printNumbers.printNumbers(2)); + Util.printArray(printNumbers.printNumbers(3)); + } + + /** + * 解题思路: + * 本题没有什么难度,唯一难的就是咋根据n构建出相应size的数组 + * + * @param n + * @return + */ + public int[] printNumbers(int n) { + char[] len = new char[n]; + for (int i = 0; i < n; i++) { + len[i] = '9'; + } + int size = Integer.parseInt(new String(len)); + int[] retVal = new int[size]; + for (int i = 0; i < size; i++) { + retVal[i] = i+1; + } + + return retVal; + } +} diff --git a/src/pp/arithmetic/offer/_18_deleteNode.java b/src/pp/arithmetic/offer/_18_deleteNode.java new file mode 100644 index 0000000..0f4dd2e --- /dev/null +++ b/src/pp/arithmetic/offer/_18_deleteNode.java @@ -0,0 +1,74 @@ +package pp.arithmetic.offer; + +import pp.arithmetic.Util; +import pp.arithmetic.model.ListNode; + +/** + * Created by wangpeng on 2020-09-09. + * 剑指 Offer 18. 删除链表的节点 + * + * 给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。 + * + * 返回删除后的链表的头节点。 + * + * 注意:此题对比原题有改动 + * + * 示例 1: + * + * 输入: head = [4,5,1,9], val = 5 + * 输出: [4,1,9] + * 解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9. + * 示例 2: + * + * 输入: head = [4,5,1,9], val = 1 + * 输出: [4,5,9] + * 解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9. + *   + * + * 说明: + * + * 题目保证链表中节点的值互不相同 + * 若使用 C 或 C++ 语言,你不需要 free 或 delete 被删除的节点 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof + * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 + */ +public class _18_deleteNode { + + public static void main(String[] args) { + _18_deleteNode deleteNode = new _18_deleteNode(); + ListNode head = new ListNode(4); + head.next = new ListNode(5); + head.next.next = new ListNode(1); + head.next.next.next = new ListNode(9); + ListNode listNode = deleteNode.deleteNode(head, 4); + Util.printListNode(listNode); + } + + /** + * 解题思路: + * 对于链表的问题,最核心的思想就是遍历,使用一个虚拟节点指向头结点,用来缓存返回结果 + * + * @param head + * @param val + * @return + */ + public ListNode deleteNode(ListNode head, int val) { + ListNode dummp = new ListNode(0); + dummp.next = head; + ListNode pre = dummp; + ListNode next = head; + while (next != null) { + if (next.val == val) { + pre.next = next.next; + next.next = null; + return dummp.next; + } + pre = next; + next = next.next; + } + + return null; + } +}