From c4d9223a3fb47c2ea425760da64a32cae5ca9426 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Tue, 26 Nov 2019 15:50:05 +0800 Subject: [PATCH 01/93] feat(MEDIUM): add _89_grayCode --- src/pp/arithmetic/leetcode/_89_grayCode.java | 71 ++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_89_grayCode.java 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; + } + +} From ee3880ce39b2c838bf55f6aa35f10bc6838edf62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Tue, 26 Nov 2019 15:52:20 +0800 Subject: [PATCH 02/93] docs: add _89_grayCode --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 37d9a0f..db4c481 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成233道 +- leetcode练习,坚持每天一道,目前已完成234道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -18,7 +18,7 @@ - [x] [88. 合并两个有序数组](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_88_merge.java) -- [ ] [89. 格雷编码](https://leetcode-cn.com/problems/gray-code/) +- [x] [89. 格雷编码](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_89_grayCode.java) - [ ] [97. 交错字符串](https://leetcode-cn.com/problems/interleaving-string/) @@ -59,9 +59,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成233) +### 题目列表(更新中—已完成234) -[Leetcode-Java(200+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_88_merge.java) +[Leetcode-Java(200+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_89_grayCode.java) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -153,6 +153,7 @@ | #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 | | From a173301f46d8fc1e3e00b7a3fe70f260cfbe57aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Thu, 28 Nov 2019 10:08:27 +0800 Subject: [PATCH 03/93] feat(HARD): add _97_isInterleave --- .../arithmetic/leetcode/_97_isInterleave.java | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_97_isInterleave.java 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; + } +} From 90ea0810c985f4552513bf1386f339dfedb3db27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Thu, 28 Nov 2019 10:12:56 +0800 Subject: [PATCH 04/93] docs: add _97_isInterleave --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index db4c481..f195313 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成234道 +- leetcode练习,坚持每天一道,目前已完成235道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -20,7 +20,7 @@ - [x] [89. 格雷编码](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_89_grayCode.java) -- [ ] [97. 交错字符串](https://leetcode-cn.com/problems/interleaving-string/) +- [x] [97. 交错字符串](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_97_isInterleave.java) - [ ] [99. 恢复二叉搜索树](https://leetcode-cn.com/problems/recover-binary-search-tree/) @@ -59,9 +59,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成234) +### 题目列表(更新中—已完成235) -[Leetcode-Java(200+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_89_grayCode.java) +[Leetcode-Java(200+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_97_isInterleave.java) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -160,6 +160,7 @@ | #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实现未想到 | +| #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 | | | #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 | | From 131403a66aa9bc431c77791a52fdcf65e18f7547 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Tue, 3 Dec 2019 14:34:32 +0800 Subject: [PATCH 05/93] feat(HARD): add _99_recoverTree --- .../arithmetic/leetcode/_99_recoverTree.java | 153 ++++++++++++++++++ 1 file changed, 153 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_99_recoverTree.java 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; + } + +} From 91143ae06c6f8395dbd9dd5e028ef301186cb45b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Tue, 3 Dec 2019 14:36:42 +0800 Subject: [PATCH 06/93] feat: add _99_recoverTree --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index f195313..eae50d0 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成235道 +- leetcode练习,坚持每天一道,目前已完成236道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -22,7 +22,7 @@ - [x] [97. 交错字符串](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_97_isInterleave.java) -- [ ] [99. 恢复二叉搜索树](https://leetcode-cn.com/problems/recover-binary-search-tree/) +- [x] [99. 恢复二叉搜索树](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_99_recoverTree.java) - [ ] [100. 相同的树](https://leetcode-cn.com/problems/same-tree/) @@ -59,9 +59,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成235) +### 题目列表(更新中—已完成236) -[Leetcode-Java(200+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_97_isInterleave.java) +[Leetcode-Java(200+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_99_recoverTree.java) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -162,6 +162,7 @@ | #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实现未想到 | | #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 | | | #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 | | From 8785b165847e57413839c2df5d28d8463c49c18e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Wed, 4 Dec 2019 10:22:35 +0800 Subject: [PATCH 07/93] feat(EASY): add _100_isSameTree --- .../arithmetic/leetcode/_100_isSameTree.java | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_100_isSameTree.java 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; + } +} From 555fa0fd01d5ce198c43d5e94fc286b82b9d5df6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Wed, 4 Dec 2019 10:26:07 +0800 Subject: [PATCH 08/93] docs: add _100_isSameTree --- README.md | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index eae50d0..816e31a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成236道 +- leetcode练习,坚持每天一道,目前已完成237道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -14,17 +14,19 @@ - [x] [83. 删除排序链表中的重复元素](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_83_deleteDuplicates.java) -- [x] [87. 扰乱字符串](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_87_isScramble.java) +- [x] [87. 扰乱字符串](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_87_isScramble.java) -- [x] [88. 合并两个有序数组](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_88_merge.java) +- [x] [88. 合并两个有序数组](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_88_merge.java) -- [x] [89. 格雷编码](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_89_grayCode.java) +- [x] [89. 格雷编码](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_89_grayCode.java) -- [x] [97. 交错字符串](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_97_isInterleave.java) +- [ ] [96. 不同的二叉搜索树](https://leetcode-cn.com/problems/unique-binary-search-trees/) -- [x] [99. 恢复二叉搜索树](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_99_recoverTree.java) +- [x] [97. 交错字符串](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_97_isInterleave.java) -- [ ] [100. 相同的树](https://leetcode-cn.com/problems/same-tree/) +- [x] [99. 恢复二叉搜索树](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_99_recoverTree.java) + +- [x] [100. 相同的树](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_100_isSameTree.java) ## 已解题目 @@ -59,9 +61,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成236) +### 题目列表(更新中—已完成237) -[Leetcode-Java(200+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_99_recoverTree.java) +[Leetcode-Java(200+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_100_isSameTree.java) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -163,6 +165,7 @@ | #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 | | From da801259ad695b8c2104a6ae3cb9141b5e6694a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Thu, 5 Dec 2019 10:58:43 +0800 Subject: [PATCH 09/93] feat(MEDIUM): add _96_numTrees --- src/pp/arithmetic/leetcode/_96_numTrees.java | 97 ++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_96_numTrees.java 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; + } +} From 0b2661c6fc6960813944a3cd91c74c16b717c3b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Sat, 7 Dec 2019 18:05:19 +0800 Subject: [PATCH 10/93] docs: add _96_numTrees --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 816e31a..f873046 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成237道 +- leetcode练习,坚持每天一道,目前已完成238道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -20,7 +20,7 @@ - [x] [89. 格雷编码](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_89_grayCode.java) -- [ ] [96. 不同的二叉搜索树](https://leetcode-cn.com/problems/unique-binary-search-trees/) +- [x] [96. 不同的二叉搜索树](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_96_numTrees.java) - [x] [97. 交错字符串](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_97_isInterleave.java) @@ -61,9 +61,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成237) +### 题目列表(更新中—已完成238) -[Leetcode-Java(200+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_100_isSameTree.java) +[Leetcode-Java(200+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_96_numTrees.java) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -162,6 +162,7 @@ | #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 | | From aad3745cbac1c06a791271077d729408b68a9dbb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Mon, 9 Dec 2019 10:00:00 +0800 Subject: [PATCH 11/93] =?UTF-8?q?docs:=20=E6=9B=B4=E6=96=B0=E9=A2=98?= =?UTF-8?q?=E7=9B=AE=E5=88=97=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index f873046..4fde0b7 100644 --- a/README.md +++ b/README.md @@ -12,21 +12,19 @@ 扫题:顺序 -- [x] [83. 删除排序链表中的重复元素](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_83_deleteDuplicates.java) +- [ ] [106. 从中序与后序遍历序列构造二叉树 -Medium](https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/) -- [x] [87. 扰乱字符串](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_87_isScramble.java) +- [ ] [107. 二叉树的层次遍历 II --Easy](https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/) -- [x] [88. 合并两个有序数组](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_88_merge.java) +- [ ] [109. 有序链表转换二叉搜索树 --Medium](https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree/) -- [x] [89. 格雷编码](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_89_grayCode.java) +- [ ] [112. 路径总和 --Easy](https://leetcode-cn.com/problems/path-sum/) -- [x] [96. 不同的二叉搜索树](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_96_numTrees.java) +- [ ] [115. 不同的子序列 --Hard](https://leetcode-cn.com/problems/distinct-subsequences/) -- [x] [97. 交错字符串](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_97_isInterleave.java) +- [ ] [116. 填充每个节点的下一个右侧节点指针 --Medium](https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/) -- [x] [99. 恢复二叉搜索树](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_99_recoverTree.java) - -- [x] [100. 相同的树](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_100_isSameTree.java) +- [ ] [117. 填充每个节点的下一个右侧节点指针 II --Medium](https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii/) ## 已解题目 From 81d62fdab7f9c0e714cd193826dc4d5ed71adf65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Mon, 9 Dec 2019 10:47:42 +0800 Subject: [PATCH 12/93] feat(MEDIUM): add _106_buildTree --- .../arithmetic/leetcode/_106_buildTree.java | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_106_buildTree.java diff --git a/src/pp/arithmetic/leetcode/_106_buildTree.java b/src/pp/arithmetic/leetcode/_106_buildTree.java new file mode 100644 index 0000000..069bdc8 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_106_buildTree.java @@ -0,0 +1,69 @@ +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,将右子树构造出来 + * + * @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; + } + +} From 8ff61e88ff485dfc3659428a29e64a40d1bf19d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Mon, 9 Dec 2019 10:50:27 +0800 Subject: [PATCH 13/93] docs: add _106_buildTree --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 4fde0b7..6f8fda8 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成238道 +- leetcode练习,坚持每天一道,目前已完成239道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -12,7 +12,7 @@ 扫题:顺序 -- [ ] [106. 从中序与后序遍历序列构造二叉树 -Medium](https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/) +- [x] [106. 从中序与后序遍历序列构造二叉树 -Medium](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_106_buildTree.java) - [ ] [107. 二叉树的层次遍历 II --Easy](https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/) @@ -59,9 +59,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成238) +### 题目列表(更新中—已完成239) -[Leetcode-Java(200+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_96_numTrees.java) +[Leetcode-Java(200+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_106_buildTree.java) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -170,6 +170,7 @@ | #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 | | | #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 | | | #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 | | From f06fab2971678ac74266015e663606839f586190 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Mon, 9 Dec 2019 10:52:23 +0800 Subject: [PATCH 14/93] =?UTF-8?q?fix:=20=E6=9B=B4=E6=96=B0=E4=BC=98?= =?UTF-8?q?=E5=8C=96=E5=BB=BA=E8=AE=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/pp/arithmetic/leetcode/_106_buildTree.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/pp/arithmetic/leetcode/_106_buildTree.java b/src/pp/arithmetic/leetcode/_106_buildTree.java index 069bdc8..5a3d6dc 100644 --- a/src/pp/arithmetic/leetcode/_106_buildTree.java +++ b/src/pp/arithmetic/leetcode/_106_buildTree.java @@ -46,6 +46,11 @@ public static void main(String[] args) { * 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 From ded30987f3b49d9d4b721ed9458c73c589e45274 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Tue, 10 Dec 2019 17:40:14 +0800 Subject: [PATCH 15/93] feat(EASY): add _107_levelOrderBottom --- .../leetcode/_107_levelOrderBottom.java | 84 +++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_107_levelOrderBottom.java 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; + } +} From 2edf5fe6f845c3196db3e5578dbf8cb0d8b9cc9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Tue, 10 Dec 2019 17:43:00 +0800 Subject: [PATCH 16/93] docs: add _107_levelOrderBottom --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 6f8fda8..7dd3f2c 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成239道 +- leetcode练习,坚持每天一道,目前已完成240道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -14,7 +14,7 @@ - [x] [106. 从中序与后序遍历序列构造二叉树 -Medium](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_106_buildTree.java) -- [ ] [107. 二叉树的层次遍历 II --Easy](https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/) +- [x] [107. 二叉树的层次遍历 II --Easy](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_107_levelOrderBottom.java) - [ ] [109. 有序链表转换二叉搜索树 --Medium](https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree/) @@ -59,9 +59,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成239) +### 题目列表(更新中—已完成240) -[Leetcode-Java(200+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_106_buildTree.java) +[Leetcode-Java(200+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_107_levelOrderBottom.java) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -171,6 +171,7 @@ | #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 | | | #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 | | From 1cd7dac0cfceff8043ffcbf213f09c8df472550f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Wed, 11 Dec 2019 11:15:26 +0800 Subject: [PATCH 17/93] feat(MEDIUM): add _109_sortedListToBST --- .../leetcode/_109_sortedListToBST.java | 89 +++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_109_sortedListToBST.java diff --git a/src/pp/arithmetic/leetcode/_109_sortedListToBST.java b/src/pp/arithmetic/leetcode/_109_sortedListToBST.java new file mode 100644 index 0000000..5d8b5a2 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_109_sortedListToBST.java @@ -0,0 +1,89 @@ +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; + } +} From b5740ef72ac8988eccf3fa8f60dcfd2581659e1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Wed, 11 Dec 2019 11:22:21 +0800 Subject: [PATCH 18/93] docs: add _109_sortedListToBST --- README.md | 9 +++++---- src/pp/arithmetic/leetcode/_109_sortedListToBST.java | 2 ++ 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 7dd3f2c..f1a49ce 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成240道 +- leetcode练习,坚持每天一道,目前已完成241道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -16,7 +16,7 @@ - [x] [107. 二叉树的层次遍历 II --Easy](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_107_levelOrderBottom.java) -- [ ] [109. 有序链表转换二叉搜索树 --Medium](https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree/) +- [x] [109. 有序链表转换二叉搜索树 --Medium]([_109_sortedListToBST.java](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_109_sortedListToBST.java)) - [ ] [112. 路径总和 --Easy](https://leetcode-cn.com/problems/path-sum/) @@ -59,9 +59,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成240) +### 题目列表(更新中—已完成241) -[Leetcode-Java(200+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_107_levelOrderBottom.java) +[Leetcode-Java(240+题解,持续更新、欢迎star&留言&交流)]([_109_sortedListToBST.java](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_109_sortedListToBST.java)) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -173,6 +173,7 @@ | #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 | | | #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 | | | #120 | [三角形最小路径和](https://leetcode-cn.com/problems/triangle/) | [MinimumTotal](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_120_minimumTotal.java) | [数组]()、[动态规划]() | Medium | | diff --git a/src/pp/arithmetic/leetcode/_109_sortedListToBST.java b/src/pp/arithmetic/leetcode/_109_sortedListToBST.java index 5d8b5a2..73355f2 100644 --- a/src/pp/arithmetic/leetcode/_109_sortedListToBST.java +++ b/src/pp/arithmetic/leetcode/_109_sortedListToBST.java @@ -48,6 +48,8 @@ public static void main(String[] args) { * 1、如何找到链表的中间位置 ==> 两次遍历,第一次使用length记录总长度,第二次取length/2的位置为更觉得 * 2、如何将一个链表分割成左右两部分独立链表 ==> 变量rightPreNode保存遍历过程中的前置节点,为断链做准备 * + * 对于难点一:也可以用快慢指针定位中间位置 + * * 链表的解法多数是遍历,利用额外的节点保存中间状态 * 树的解法多数是递归,同样的入参生成左右子树 * From 17026d60a2e3876b90437580b6051fcef2c7bcc4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Thu, 12 Dec 2019 11:20:05 +0800 Subject: [PATCH 19/93] feat(EASY): add _110_isBalanced --- README.md | 4 + src/pp/arithmetic/Util.java | 31 ++++++++ .../arithmetic/leetcode/_110_isBalanced.java | 73 +++++++++++++++++++ 3 files changed, 108 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_110_isBalanced.java diff --git a/README.md b/README.md index f1a49ce..56f3561 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,10 @@ - [x] [109. 有序链表转换二叉搜索树 --Medium]([_109_sortedListToBST.java](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_109_sortedListToBST.java)) +- [ ] [110. 平衡二叉树](https://leetcode-cn.com/problems/balanced-binary-tree/) + +- [ ] [111. 二叉树的最小深度](https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/) + - [ ] [112. 路径总和 --Easy](https://leetcode-cn.com/problems/path-sum/) - [ ] [115. 不同的子序列 --Hard](https://leetcode-cn.com/problems/distinct-subsequences/) diff --git a/src/pp/arithmetic/Util.java b/src/pp/arithmetic/Util.java index 4db874e..c377a67 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] + " "); 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); + } +} From ebda09862aaf61427e40ebe57508f818cc985ece Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Thu, 12 Dec 2019 11:36:37 +0800 Subject: [PATCH 20/93] feat(EASY): add _111_minDepth --- README.md | 4 +- src/pp/arithmetic/leetcode/_111_minDepth.java | 55 +++++++++++++++++++ 2 files changed, 57 insertions(+), 2 deletions(-) create mode 100644 src/pp/arithmetic/leetcode/_111_minDepth.java diff --git a/README.md b/README.md index 56f3561..75b55cc 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ - [x] [109. 有序链表转换二叉搜索树 --Medium]([_109_sortedListToBST.java](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_109_sortedListToBST.java)) -- [ ] [110. 平衡二叉树](https://leetcode-cn.com/problems/balanced-binary-tree/) +- [x] [110. 平衡二叉树 --Easy](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_110_isBalanced.java) - [ ] [111. 二叉树的最小深度](https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/) @@ -65,7 +65,7 @@ ### 题目列表(更新中—已完成241) -[Leetcode-Java(240+题解,持续更新、欢迎star&留言&交流)]([_109_sortedListToBST.java](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_109_sortedListToBST.java)) +[Leetcode-Java(240+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_110_isBalanced.java) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | 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; + } +} From b15bb3400cca40d84d73d35baef9c80718a7d395 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Thu, 12 Dec 2019 11:39:44 +0800 Subject: [PATCH 21/93] docs: add 110&111 --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 75b55cc..699b256 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ - [x] [110. 平衡二叉树 --Easy](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_110_isBalanced.java) -- [ ] [111. 二叉树的最小深度](https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/) +- [x] [111. 二叉树的最小深度](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_111_minDepth.java) - [ ] [112. 路径总和 --Easy](https://leetcode-cn.com/problems/path-sum/) @@ -65,7 +65,7 @@ ### 题目列表(更新中—已完成241) -[Leetcode-Java(240+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_110_isBalanced.java) +[Leetcode-Java(240+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_111_minDepth.java) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -178,6 +178,8 @@ | #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 | | | #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 | | | #120 | [三角形最小路径和](https://leetcode-cn.com/problems/triangle/) | [MinimumTotal](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_120_minimumTotal.java) | [数组]()、[动态规划]() | Medium | | From df0da65701ccd734bbf935d90ad5090181455d3b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Thu, 12 Dec 2019 12:04:09 +0800 Subject: [PATCH 22/93] feat(EASY): add _112_hasPathSum --- .../arithmetic/leetcode/_112_hasPathSum.java | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_112_hasPathSum.java 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; + } +} From 2ab67438c70e1779b5eb649caa8907da576d181c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Thu, 12 Dec 2019 12:09:02 +0800 Subject: [PATCH 23/93] docs: add _112_hasPathSum --- README.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 699b256..22515d7 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成241道 +- leetcode练习,坚持每天一道,目前已完成242道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -20,9 +20,9 @@ - [x] [110. 平衡二叉树 --Easy](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_110_isBalanced.java) -- [x] [111. 二叉树的最小深度](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_111_minDepth.java) +- [x] [111. 二叉树的最小深度 --Easy](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_111_minDepth.java) -- [ ] [112. 路径总和 --Easy](https://leetcode-cn.com/problems/path-sum/) +- [x] [112. 路径总和 --Easy](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_112_hasPathSum.java) - [ ] [115. 不同的子序列 --Hard](https://leetcode-cn.com/problems/distinct-subsequences/) @@ -63,9 +63,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成241) +### 题目列表(更新中—已完成242) -[Leetcode-Java(240+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_111_minDepth.java) +[Leetcode-Java(240+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_112_hasPathSum.java) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -180,6 +180,7 @@ | #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 | | | #120 | [三角形最小路径和](https://leetcode-cn.com/problems/triangle/) | [MinimumTotal](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_120_minimumTotal.java) | [数组]()、[动态规划]() | Medium | | From a423cd248874e1e7801f6bec86abc126c55cbf1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Sat, 14 Dec 2019 11:16:21 +0800 Subject: [PATCH 24/93] feat(HARD): add _115_numDistinct --- .../arithmetic/leetcode/_115_numDistinct.java | 139 ++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_115_numDistinct.java diff --git a/src/pp/arithmetic/leetcode/_115_numDistinct.java b/src/pp/arithmetic/leetcode/_115_numDistinct.java new file mode 100644 index 0000000..d5af50a --- /dev/null +++ b/src/pp/arithmetic/leetcode/_115_numDistinct.java @@ -0,0 +1,139 @@ +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 + * + * 优化思考:是不是可以考虑将遍历过程中的一些结果保存起来,而不是每次凑重新计算==>动态规划 + * + * @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] + * + * @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()]; + } +} From 47a28def53332b5f6f6213327d315e155b53b171 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Sat, 14 Dec 2019 11:21:47 +0800 Subject: [PATCH 25/93] docs: add _115_numDistinct --- README.md | 9 +++++---- src/pp/arithmetic/leetcode/_115_numDistinct.java | 5 ++++- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 22515d7..3a88def 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成242道 +- leetcode练习,坚持每天一道,目前已完成243道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -24,7 +24,7 @@ - [x] [112. 路径总和 --Easy](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_112_hasPathSum.java) -- [ ] [115. 不同的子序列 --Hard](https://leetcode-cn.com/problems/distinct-subsequences/) +- [x] [115. 不同的子序列 --Hard](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_115_numDistinct.java) - [ ] [116. 填充每个节点的下一个右侧节点指针 --Medium](https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/) @@ -63,9 +63,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成242) +### 题目列表(更新中—已完成243) -[Leetcode-Java(240+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_112_hasPathSum.java) +[Leetcode-Java(240+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_115_numDistinct.java) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -183,6 +183,7 @@ | #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 | | | #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 | | diff --git a/src/pp/arithmetic/leetcode/_115_numDistinct.java b/src/pp/arithmetic/leetcode/_115_numDistinct.java index d5af50a..1610c0b 100644 --- a/src/pp/arithmetic/leetcode/_115_numDistinct.java +++ b/src/pp/arithmetic/leetcode/_115_numDistinct.java @@ -79,7 +79,7 @@ public static void main(String[] args) { * "bcddceeeebecbc" * 本地跑出结果:700531452 * - * 优化思考:是不是可以考虑将遍历过程中的一些结果保存起来,而不是每次凑重新计算==>动态规划 + * 优化思考:是不是可以考虑将遍历过程中的一些结果保存起来,而不是每次凑重新计算==>动态规划{@link _115_numDistinct#numDistinct2(String, String)} * * @param s * @param t @@ -118,6 +118,9 @@ public int numDistinct(String s, String t) { * 如果某一位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 From 986742580c5b30910ee1616794ed93f462ed1a27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Sat, 14 Dec 2019 15:21:29 +0800 Subject: [PATCH 26/93] feat(MEDIUM): add _116_connect --- src/pp/arithmetic/leetcode/_116_connect.java | 81 ++++++++++++++++++++ src/pp/arithmetic/model/Node.java | 24 ++++++ 2 files changed, 105 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_116_connect.java create mode 100644 src/pp/arithmetic/model/Node.java 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/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; + } +} From fa3f26ad21df9b1e3e2d44e9fe243abf1cc4dc5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Sat, 14 Dec 2019 15:26:11 +0800 Subject: [PATCH 27/93] docs: add _116_connect --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 3a88def..2a5a1be 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成243道 +- leetcode练习,坚持每天一道,目前已完成244道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -26,7 +26,7 @@ - [x] [115. 不同的子序列 --Hard](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_115_numDistinct.java) -- [ ] [116. 填充每个节点的下一个右侧节点指针 --Medium](https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/) +- [x] [116. 填充每个节点的下一个右侧节点指针 --Medium](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_116_connect.java) - [ ] [117. 填充每个节点的下一个右侧节点指针 II --Medium](https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii/) @@ -63,9 +63,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成243) +### 题目列表(更新中—已完成244) -[Leetcode-Java(240+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_115_numDistinct.java) +[Leetcode-Java(240+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_116_connect.java) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -184,6 +184,7 @@ | #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 | | | #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 | | From bef7cb6921d64759f98f5c6de576cfe001d9d02c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Tue, 17 Dec 2019 15:36:30 +0800 Subject: [PATCH 28/93] feat(MEDIUM): add _117_connect --- src/pp/arithmetic/leetcode/_117_connect.java | 97 ++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_117_connect.java 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; + } + +} From 9cf5f192c80d04b9d42c3babe5074f1d51ac9d62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Tue, 17 Dec 2019 15:40:38 +0800 Subject: [PATCH 29/93] docs: add _117_connect --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 2a5a1be..6721fe7 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成244道 +- leetcode练习,坚持每天一道,目前已完成245道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -28,7 +28,7 @@ - [x] [116. 填充每个节点的下一个右侧节点指针 --Medium](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_116_connect.java) -- [ ] [117. 填充每个节点的下一个右侧节点指针 II --Medium](https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii/) +- [x] [117. 填充每个节点的下一个右侧节点指针 II --Medium](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_117_connect.java) ## 已解题目 @@ -63,9 +63,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成244) +### 题目列表(更新中—已完成245) -[Leetcode-Java(240+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_116_connect.java) +[Leetcode-Java(240+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_117_connect.java) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -185,6 +185,7 @@ | #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 | | | #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 | | From 65342a8766e3f9ec44ef7fa3e33ecce372601aa1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Wed, 18 Dec 2019 09:40:09 +0800 Subject: [PATCH 30/93] =?UTF-8?q?docs:=20=E6=9B=B4=E6=96=B0=E9=A2=98?= =?UTF-8?q?=E7=9B=AE=E5=88=97=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 6721fe7..5a83f68 100644 --- a/README.md +++ b/README.md @@ -12,23 +12,19 @@ 扫题:顺序 -- [x] [106. 从中序与后序遍历序列构造二叉树 -Medium](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_106_buildTree.java) +- [ ] [118. 杨辉三角](https://leetcode-cn.com/problems/pascals-triangle/) -- [x] [107. 二叉树的层次遍历 II --Easy](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_107_levelOrderBottom.java) +- [ ] [119. 杨辉三角 II](https://leetcode-cn.com/problems/pascals-triangle-ii/) -- [x] [109. 有序链表转换二叉搜索树 --Medium]([_109_sortedListToBST.java](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_109_sortedListToBST.java)) +- [ ] [129. 求根到叶子节点数字之和](https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/) -- [x] [110. 平衡二叉树 --Easy](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_110_isBalanced.java) +- [ ] [130. 被围绕的区域](https://leetcode-cn.com/problems/surrounded-regions/) -- [x] [111. 二叉树的最小深度 --Easy](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_111_minDepth.java) +- [ ] [131. 分割回文串](https://leetcode-cn.com/problems/palindrome-partitioning/) -- [x] [112. 路径总和 --Easy](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_112_hasPathSum.java) +- [ ] [132. 分割回文串 II](https://leetcode-cn.com/problems/palindrome-partitioning-ii/) -- [x] [115. 不同的子序列 --Hard](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_115_numDistinct.java) - -- [x] [116. 填充每个节点的下一个右侧节点指针 --Medium](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_116_connect.java) - -- [x] [117. 填充每个节点的下一个右侧节点指针 II --Medium](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_117_connect.java) +- [ ] [133. 克隆图](https://leetcode-cn.com/problems/clone-graph/) ## 已解题目 From 8e8063c79b4d0a3a710f5178d1f1a1e2b9596dfb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Wed, 18 Dec 2019 09:56:03 +0800 Subject: [PATCH 31/93] feat(EASY): add _118_generate --- src/pp/arithmetic/leetcode/_118_generate.java | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_118_generate.java 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; + } +} From 50e04c27f57ac3f123b85aa71ca4da6393ff94b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Wed, 18 Dec 2019 09:58:20 +0800 Subject: [PATCH 32/93] docs: add _118_generate --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 5a83f68..145c3ce 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成245道 +- leetcode练习,坚持每天一道,目前已完成246道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -12,7 +12,7 @@ 扫题:顺序 -- [ ] [118. 杨辉三角](https://leetcode-cn.com/problems/pascals-triangle/) +- [x] [118. 杨辉三角](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_118_generate.java) - [ ] [119. 杨辉三角 II](https://leetcode-cn.com/problems/pascals-triangle-ii/) @@ -59,9 +59,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成245) +### 题目列表(更新中—已完成246) -[Leetcode-Java(240+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_117_connect.java) +[Leetcode-Java(240+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_118_generate.java) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -182,6 +182,7 @@ | #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 | | | #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 | | From 338e617276db3b28b15b55a241266a3070a72733 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Wed, 18 Dec 2019 10:50:02 +0800 Subject: [PATCH 33/93] feat(EASY): add _119_getRow --- src/pp/arithmetic/leetcode/_119_getRow.java | 61 +++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_119_getRow.java 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; + } +} From e1ad7ea0447b575f4c5d7e6befa71243624e536d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Wed, 18 Dec 2019 10:57:04 +0800 Subject: [PATCH 34/93] docs: add _119_getRow --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 145c3ce..20e94c9 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成246道 +- leetcode练习,坚持每天一道,目前已完成247道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -14,7 +14,7 @@ - [x] [118. 杨辉三角](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_118_generate.java) -- [ ] [119. 杨辉三角 II](https://leetcode-cn.com/problems/pascals-triangle-ii/) +- [x] [119. 杨辉三角 II](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_119_getRow.java) - [ ] [129. 求根到叶子节点数字之和](https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/) @@ -59,9 +59,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成246) +### 题目列表(更新中—已完成247) -[Leetcode-Java(240+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_118_generate.java) +[Leetcode-Java(240+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_119_getRow.java) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -183,6 +183,7 @@ | #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 | | From 25d3ab7f76ff07420fae271a7ba96dee4e48fbca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Mon, 23 Dec 2019 11:47:18 +0800 Subject: [PATCH 35/93] feat(MEDIUM): add _129_sumNumbers --- .../arithmetic/leetcode/_129_sumNumbers.java | 84 +++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_129_sumNumbers.java 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); + } + } + +} From ed9006d08e530d300add908e71ddeed70726b2ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Mon, 23 Dec 2019 11:50:48 +0800 Subject: [PATCH 36/93] docs: add _129_sumNumbers --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 20e94c9..e760dc6 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成247道 +- leetcode练习,坚持每天一道,目前已完成248道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -16,7 +16,7 @@ - [x] [119. 杨辉三角 II](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_119_getRow.java) -- [ ] [129. 求根到叶子节点数字之和](https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/) +- [x] [129. 求根到叶子节点数字之和](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_129_sumNumbers.java) - [ ] [130. 被围绕的区域](https://leetcode-cn.com/problems/surrounded-regions/) @@ -59,9 +59,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成247) +### 题目列表(更新中—已完成248) -[Leetcode-Java(240+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_119_getRow.java) +[Leetcode-Java(240+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_129_sumNumbers.java) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -193,6 +193,7 @@ | #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 | | | #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 | 回溯实现耗时 | From af25dac177d46fa609684c1efdea1cea8d6f91c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Mon, 23 Dec 2019 19:53:56 +0800 Subject: [PATCH 37/93] feat(MEDIUM): add _130_solve --- src/pp/arithmetic/leetcode/_130_solve.java | 88 ++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_130_solve.java 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); // 右 + } +} From 4df519d972d1e5a1495723163d94791d9f6154a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Mon, 23 Dec 2019 19:57:07 +0800 Subject: [PATCH 38/93] docs: add _130_solve --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index e760dc6..f9a610e 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成248道 +- leetcode练习,坚持每天一道,目前已完成249道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -18,7 +18,7 @@ - [x] [129. 求根到叶子节点数字之和](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_129_sumNumbers.java) -- [ ] [130. 被围绕的区域](https://leetcode-cn.com/problems/surrounded-regions/) +- [x] [130. 被围绕的区域](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_130_solve.java) - [ ] [131. 分割回文串](https://leetcode-cn.com/problems/palindrome-partitioning/) @@ -59,9 +59,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成248) +### 题目列表(更新中—已完成249) -[Leetcode-Java(240+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_129_sumNumbers.java) +[Leetcode-Java(240+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_130_solve.java) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -194,6 +194,7 @@ | #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 | | | #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 | 回溯实现耗时 | From a6682ecb38baa4e0513c7c609c215890c4206ee4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Thu, 26 Dec 2019 11:36:20 +0800 Subject: [PATCH 39/93] feat(MEDIUM): add _131_partition --- src/pp/arithmetic/Util.java | 11 +++ .../arithmetic/leetcode/_131_partition.java | 85 +++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_131_partition.java diff --git a/src/pp/arithmetic/Util.java b/src/pp/arithmetic/Util.java index c377a67..7e38661 100644 --- a/src/pp/arithmetic/Util.java +++ b/src/pp/arithmetic/Util.java @@ -147,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"); 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; + } +} From 36e62306f221c339bc519bedd502afaac9328bc3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Thu, 26 Dec 2019 11:43:23 +0800 Subject: [PATCH 40/93] docs: add _131_partition --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index f9a610e..0d9d052 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成249道 +- leetcode练习,坚持每天一道,目前已完成250道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -20,7 +20,7 @@ - [x] [130. 被围绕的区域](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_130_solve.java) -- [ ] [131. 分割回文串](https://leetcode-cn.com/problems/palindrome-partitioning/) +- [x] [131. 分割回文串](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_131_partition.java) - [ ] [132. 分割回文串 II](https://leetcode-cn.com/problems/palindrome-partitioning-ii/) @@ -59,9 +59,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成249) +### 题目列表(更新中—已完成250) -[Leetcode-Java(240+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_130_solve.java) +[Leetcode-Java(250+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_131_partition.java) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -195,6 +195,7 @@ | #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 | | | #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 | 回溯实现耗时 | From 73f0aaec3d706fef0e07971817133106ac78e4f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Tue, 31 Dec 2019 11:14:19 +0800 Subject: [PATCH 41/93] feat(HARD): add _132_minCut --- src/pp/arithmetic/leetcode/_132_minCut.java | 57 +++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_132_minCut.java 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]; + + } +} From 7e48309b0e9f14f9532f79310af1b2be7fd4a616 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Tue, 31 Dec 2019 11:15:59 +0800 Subject: [PATCH 42/93] docs: add _132_minCut --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 0d9d052..14ee630 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成250道 +- leetcode练习,坚持每天一道,目前已完成251道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -22,7 +22,7 @@ - [x] [131. 分割回文串](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_131_partition.java) -- [ ] [132. 分割回文串 II](https://leetcode-cn.com/problems/palindrome-partitioning-ii/) +- [x] [132. 分割回文串 II](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_132_minCut.java) - [ ] [133. 克隆图](https://leetcode-cn.com/problems/clone-graph/) @@ -59,9 +59,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成250) +### 题目列表(更新中—已完成251) -[Leetcode-Java(250+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_131_partition.java) +[Leetcode-Java(250+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_132_minCut.java) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -196,6 +196,7 @@ | #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 | | | #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 | 回溯实现耗时 | From 50bc0944629f74618038b47f9dfb6e58bb7859e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Mon, 20 Jan 2020 17:22:29 +0800 Subject: [PATCH 43/93] feat(MEDIUM): add _133_cloneGraph --- .../arithmetic/leetcode/_133_cloneGraph.java | 138 ++++++++++++++++++ 1 file changed, 138 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_133_cloneGraph.java 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; + } +} From 9ed132feb9dcb7da183999b72a3369b70d47cba5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Mon, 20 Jan 2020 17:26:00 +0800 Subject: [PATCH 44/93] docs: add _133_cloneGraph --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 14ee630..501762a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成251道 +- leetcode练习,坚持每天一道,目前已完成252道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -10,7 +10,7 @@ - 网址:https://leetcode-cn.com/ ## 待解题目列表 -扫题:顺序 +2020春节放假停更,祝大家越码越溜~ - [x] [118. 杨辉三角](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_118_generate.java) @@ -24,7 +24,7 @@ - [x] [132. 分割回文串 II](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_132_minCut.java) -- [ ] [133. 克隆图](https://leetcode-cn.com/problems/clone-graph/) +- [x] [133. 克隆图](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_133_cloneGraph.java) ## 已解题目 @@ -61,7 +61,7 @@ ### 题目列表(更新中—已完成251) -[Leetcode-Java(250+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_132_minCut.java) +[Leetcode-Java(250+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_133_cloneGraph.java) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -197,6 +197,7 @@ | #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 | 回溯实现耗时 | From b5e02f301fdfcfcb8f63c26910e11a8755e745bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Mon, 9 Mar 2020 11:48:28 +0800 Subject: [PATCH 45/93] =?UTF-8?q?docs:=20=E6=9B=B4=E6=96=B0=E5=A4=9A?= =?UTF-8?q?=E7=BA=BF=E7=A8=8B=E9=A2=98=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 501762a..3af0e13 100644 --- a/README.md +++ b/README.md @@ -10,21 +10,19 @@ - 网址:https://leetcode-cn.com/ ## 待解题目列表 -2020春节放假停更,祝大家越码越溜~ +2020疫情,安全复工~ ~多线程专题 -- [x] [118. 杨辉三角](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_118_generate.java) +- [ ] [1114. 按序打印](https://leetcode-cn.com/problems/print-in-order/) -- [x] [119. 杨辉三角 II](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_119_getRow.java) +- [ ] [1115. 交替打印FooBar](https://leetcode-cn.com/problems/print-foobar-alternately/) -- [x] [129. 求根到叶子节点数字之和](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_129_sumNumbers.java) +- [ ] [1116. 打印零与奇偶数](https://leetcode-cn.com/problems/print-zero-even-odd/) -- [x] [130. 被围绕的区域](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_130_solve.java) +- [ ] [1117. H2O 生成](https://leetcode-cn.com/problems/building-h2o/) -- [x] [131. 分割回文串](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_131_partition.java) +- [ ] [1195. 交替打印字符串](https://leetcode-cn.com/problems/fizz-buzz-multithreaded/) -- [x] [132. 分割回文串 II](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_132_minCut.java) - -- [x] [133. 克隆图](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_133_cloneGraph.java) +- [ ] [1226. 哲学家进餐](https://leetcode-cn.com/problems/the-dining-philosophers/) ## 已解题目 From 11e2d056eb9f067d831ea8cb3d4b709487a5ac66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Fri, 13 Mar 2020 11:46:32 +0800 Subject: [PATCH 46/93] feat(EASY): add _1114_Foo --- src/pp/arithmetic/leetcode/_1114_Foo.java | 116 ++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_1114_Foo.java diff --git a/src/pp/arithmetic/leetcode/_1114_Foo.java b/src/pp/arithmetic/leetcode/_1114_Foo.java new file mode 100644 index 0000000..8fe9439 --- /dev/null +++ b/src/pp/arithmetic/leetcode/_1114_Foo.java @@ -0,0 +1,116 @@ +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(); + } + } +} From d0fc32cc1305a1b31a99380413586754d9429dde Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Fri, 13 Mar 2020 11:49:33 +0800 Subject: [PATCH 47/93] docs: add _1114_Foo --- README.md | 9 +++++---- src/pp/arithmetic/leetcode/_1114_Foo.java | 1 + 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 3af0e13..8b8732f 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成252道 +- leetcode练习,坚持每天一道,目前已完成253道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -12,7 +12,7 @@ 2020疫情,安全复工~ ~多线程专题 -- [ ] [1114. 按序打印](https://leetcode-cn.com/problems/print-in-order/) +- [x] [1114. 按序打印](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1114_Foo.java) - [ ] [1115. 交替打印FooBar](https://leetcode-cn.com/problems/print-foobar-alternately/) @@ -57,9 +57,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成251) +### 题目列表(更新中—已完成253) -[Leetcode-Java(250+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_133_cloneGraph.java) +[Leetcode-Java(250+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1114_Foo.java) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -306,6 +306,7 @@ | #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 | | LCP diff --git a/src/pp/arithmetic/leetcode/_1114_Foo.java b/src/pp/arithmetic/leetcode/_1114_Foo.java index 8fe9439..c78916a 100644 --- a/src/pp/arithmetic/leetcode/_1114_Foo.java +++ b/src/pp/arithmetic/leetcode/_1114_Foo.java @@ -81,6 +81,7 @@ public void run() { } + //一道题自己没有跑成功,不知道测试用例如何输出的 static class Foo { private AtomicInteger firstJobDone = new AtomicInteger(0); From 635a3424a14180048f7600bb81ec907b77301d3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Wed, 8 Jul 2020 16:07:04 +0800 Subject: [PATCH 48/93] feat(MEDIUM): add _1115_FooBar --- src/pp/arithmetic/leetcode/_1115_FooBar.java | 111 +++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_1115_FooBar.java 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(); + } + } + } +} From bc10ce68a6fa05d002e19a5ebe771d027530f1d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Wed, 8 Jul 2020 16:10:12 +0800 Subject: [PATCH 49/93] docs: add _1115_FooBar --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 8b8732f..c3b5a84 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ - [x] [1114. 按序打印](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1114_Foo.java) -- [ ] [1115. 交替打印FooBar](https://leetcode-cn.com/problems/print-foobar-alternately/) +- [x] [1115. 交替打印FooBar](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1115_FooBar.java) - [ ] [1116. 打印零与奇偶数](https://leetcode-cn.com/problems/print-zero-even-odd/) @@ -57,9 +57,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成253) +### 题目列表(更新中—已完成254) -[Leetcode-Java(250+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1114_Foo.java) +[Leetcode-Java(250+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1115_FooBar.java) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -307,6 +307,7 @@ | #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 | | LCP From be8cdefc1ac4d3f2e871f8845d456a7a889c0f52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Tue, 14 Jul 2020 11:14:08 +0800 Subject: [PATCH 50/93] feat(MEDIUM): add _1116_ZeroEvenOdd --- .../leetcode/_1116_ZeroEvenOdd.java | 125 ++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_1116_ZeroEvenOdd.java 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(); + } + } + } +} From 033706c2854c68e504e05c32735fa0cca5ff0a01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Tue, 14 Jul 2020 11:33:13 +0800 Subject: [PATCH 51/93] docs: add _1116_ZeroEvenOdd --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c3b5a84..6399072 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ - [x] [1115. 交替打印FooBar](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1115_FooBar.java) -- [ ] [1116. 打印零与奇偶数](https://leetcode-cn.com/problems/print-zero-even-odd/) +- [x] [1116. 打印零与奇偶数](https://leetcode-cn.com/problems/print-zero-even-odd/) - [ ] [1117. H2O 生成](https://leetcode-cn.com/problems/building-h2o/) @@ -57,9 +57,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成254) +### 题目列表(更新中—已完成255) -[Leetcode-Java(250+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1115_FooBar.java) +[Leetcode-Java(250+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1116_ZeroEvenOdd.java) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -308,6 +308,7 @@ | #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 | | LCP From 22c6c1c595905f8841fb09e632c8a45e5aee226f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Wed, 15 Jul 2020 14:26:22 +0800 Subject: [PATCH 52/93] feat(MEDIUM): add _1117_H2O --- src/pp/arithmetic/leetcode/_1117_H2O.java | 196 ++++++++++++++++++++++ 1 file changed, 196 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_1117_H2O.java diff --git a/src/pp/arithmetic/leetcode/_1117_H2O.java b/src/pp/arithmetic/leetcode/_1117_H2O.java new file mode 100644 index 0000000..3d9661f --- /dev/null +++ b/src/pp/arithmetic/leetcode/_1117_H2O.java @@ -0,0 +1,196 @@ +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(); + } + } + } +} From 4bb02b0a4cebb0b63715ec998258a4335de7e82f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Wed, 15 Jul 2020 14:31:58 +0800 Subject: [PATCH 53/93] docs: add _1117_H2O --- README.md | 5 +++-- src/pp/arithmetic/leetcode/_1117_H2O.java | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6399072..e9dc433 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ - [x] [1116. 打印零与奇偶数](https://leetcode-cn.com/problems/print-zero-even-odd/) -- [ ] [1117. H2O 生成](https://leetcode-cn.com/problems/building-h2o/) +- [x] [1117. H2O 生成](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1116_ZeroEvenOdd.java) - [ ] [1195. 交替打印字符串](https://leetcode-cn.com/problems/fizz-buzz-multithreaded/) @@ -57,7 +57,7 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成255) +### 题目列表(更新中—已完成256) [Leetcode-Java(250+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1116_ZeroEvenOdd.java) @@ -309,6 +309,7 @@ | #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 | | LCP diff --git a/src/pp/arithmetic/leetcode/_1117_H2O.java b/src/pp/arithmetic/leetcode/_1117_H2O.java index 3d9661f..79a195e 100644 --- a/src/pp/arithmetic/leetcode/_1117_H2O.java +++ b/src/pp/arithmetic/leetcode/_1117_H2O.java @@ -95,6 +95,7 @@ public void run() { } } + //使用系统类进行优化 class H2O2 { private Semaphore hs; From 0e86375c901b214485edf10e0fb1a8cab2c79afd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Thu, 16 Jul 2020 14:24:04 +0800 Subject: [PATCH 54/93] feat(MEDIUM): add _1195_FizzBuzz --- .../arithmetic/leetcode/_1195_FizzBuzz.java | 187 ++++++++++++++++++ 1 file changed, 187 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_1195_FizzBuzz.java 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(); + } + } + } +} From f3930af7e6e1bac9d158fbe0401f3fd389a4f916 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Thu, 16 Jul 2020 14:34:12 +0800 Subject: [PATCH 55/93] docs: add _1195_FizzBuzz --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e9dc433..7ba3d7d 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ - [x] [1117. H2O 生成](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1116_ZeroEvenOdd.java) -- [ ] [1195. 交替打印字符串](https://leetcode-cn.com/problems/fizz-buzz-multithreaded/) +- [x] [1195. 交替打印字符串](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1195_FizzBuzz.java) - [ ] [1226. 哲学家进餐](https://leetcode-cn.com/problems/the-dining-philosophers/) @@ -57,9 +57,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成256) +### 题目列表(更新中—已完成257) -[Leetcode-Java(250+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1116_ZeroEvenOdd.java) +[Leetcode-Java(250+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1195_FizzBuzz.java) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -310,6 +310,7 @@ | #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 | | LCP From a21f888a999bfb29975d5e3b254bb0426e09ca2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Wed, 22 Jul 2020 12:00:00 +0800 Subject: [PATCH 56/93] feat(MEDIUM): add _1226_DiningPhilosophers --- .../leetcode/_1226_DiningPhilosophers.java | 155 ++++++++++++++++++ 1 file changed, 155 insertions(+) create mode 100644 src/pp/arithmetic/leetcode/_1226_DiningPhilosophers.java 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(); + } + } +} From ed1465a92ebe0237ee23d11f3cbd917ddafb8955 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Wed, 22 Jul 2020 12:02:13 +0800 Subject: [PATCH 57/93] docs: add _1226_DiningPhilosophers --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 7ba3d7d..a90c97e 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成253道 +- leetcode练习,坚持每天一道,目前已完成258道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -22,7 +22,7 @@ - [x] [1195. 交替打印字符串](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1195_FizzBuzz.java) -- [ ] [1226. 哲学家进餐](https://leetcode-cn.com/problems/the-dining-philosophers/) +- [x] [1226. 哲学家进餐](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1226_DiningPhilosophers.java/) ## 已解题目 @@ -57,9 +57,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成257) +### 题目列表(更新中—已完成258) -[Leetcode-Java(250+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1195_FizzBuzz.java) +[Leetcode-Java(250+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1226_DiningPhilosophers.java) | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | @@ -311,6 +311,7 @@ | #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 From f1d86f2a5bbc4a4d80497c7b8fa478d07ea80283 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Tue, 28 Jul 2020 10:30:33 +0800 Subject: [PATCH 58/93] =?UTF-8?q?docs:=20=E6=9B=B4=E6=96=B0=E5=89=91?= =?UTF-8?q?=E6=8C=87offer=E4=B8=93=E9=A2=98=E7=B3=BB=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index a90c97e..032ada9 100644 --- a/README.md +++ b/README.md @@ -10,19 +10,15 @@ - 网址:https://leetcode-cn.com/ ## 待解题目列表 -2020疫情,安全复工~ ~多线程专题 +剑指offer系列-持续多月,每周7题 -- [x] [1114. 按序打印](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1114_Foo.java) - -- [x] [1115. 交替打印FooBar](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1115_FooBar.java) - -- [x] [1116. 打印零与奇偶数](https://leetcode-cn.com/problems/print-zero-even-odd/) - -- [x] [1117. H2O 生成](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1116_ZeroEvenOdd.java) - -- [x] [1195. 交替打印字符串](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1195_FizzBuzz.java) - -- [x] [1226. 哲学家进餐](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1226_DiningPhilosophers.java/) +- [ ] [数组中重复的数字](https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof) +- [ ] [二维数组中的查找](https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof) +- [ ] [替换空格](https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof) +- [ ] [从尾到头打印链表](https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof) +- [ ] [重建二叉树](https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof) +- [ ] [用两个栈实现队列](https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof) +- [ ] [斐波那契数列](https://leetcode-cn.com/problems/fei-bo-na-qi-shu-lie-lcof) ## 已解题目 From 000960f50ff0cc7cdc24059d571836b5965c5720 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Tue, 28 Jul 2020 11:18:12 +0800 Subject: [PATCH 59/93] feat(offer-easy): add _03_findRepeatNumber --- .../offer/_03_findRepeatNumber.java | 124 ++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 src/pp/arithmetic/offer/_03_findRepeatNumber.java 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; + + } +} From 2ad0b63990243c84137b0ba38aa3ac91122362a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Tue, 28 Jul 2020 11:21:25 +0800 Subject: [PATCH 60/93] docs: add _03_findRepeatNumber --- README.md | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 032ada9..026b456 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成258道 +- leetcode练习,坚持每天一道,目前已完成259道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -12,7 +12,7 @@ 剑指offer系列-持续多月,每周7题 -- [ ] [数组中重复的数字](https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof) +- [x] [数组中重复的数字](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_03_findRepeatNumber.java) - [ ] [二维数组中的查找](https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof) - [ ] [替换空格](https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof) - [ ] [从尾到头打印链表](https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof) @@ -53,9 +53,19 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成258) +### 题目列表(更新中—已完成259) -[Leetcode-Java(250+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/leetcode/_1226_DiningPhilosophers.java) +[Leetcode-Java(250+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_03_findRepeatNumber.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 | +| | | | | +| | | | | + +经典题解 | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | From 6b1ce49210fc9afb469d2974fb3e981f22a5023b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Thu, 30 Jul 2020 10:34:26 +0800 Subject: [PATCH 61/93] feat(EASY): add _04_findNumberIn2DArray --- .../offer/_04_findNumberIn2DArray.java | 135 ++++++++++++++++++ 1 file changed, 135 insertions(+) create mode 100644 src/pp/arithmetic/offer/_04_findNumberIn2DArray.java 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; + } + +} From 0be19a8268a492c16a9ebc76fd1961b2597a3fb8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Thu, 30 Jul 2020 10:37:14 +0800 Subject: [PATCH 62/93] docs: add _04_findNumberIn2DArray --- README.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 026b456..a4d8faa 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成259道 +- leetcode练习,坚持每天一道,目前已完成260道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -13,7 +13,7 @@ 剑指offer系列-持续多月,每周7题 - [x] [数组中重复的数字](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_03_findRepeatNumber.java) -- [ ] [二维数组中的查找](https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof) +- [x] [二维数组中的查找](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_04_findNumberIn2DArray.java) - [ ] [替换空格](https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof) - [ ] [从尾到头打印链表](https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof) - [ ] [重建二叉树](https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof) @@ -53,19 +53,19 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成259) +### 题目列表(更新中—已完成260) -[Leetcode-Java(250+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_03_findRepeatNumber.java) +[Leetcode-Java(260+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_04_findNumberIn2DArray.java) -剑指offer系列 +#### 剑指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 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 | | +| | | | | | -经典题解 +#### 经典题解 | No | 题目 | 解决方案 | 相关话题 | 难度 | 备注 | | ----- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | From 961e224b2bc74619aa2735b66d2b92129a446c6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Thu, 30 Jul 2020 11:13:05 +0800 Subject: [PATCH 63/93] feat(EASY): add _05_replaceSpace --- src/pp/arithmetic/offer/_05_replaceSpace.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 src/pp/arithmetic/offer/_05_replaceSpace.java 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(); + } +} From 977a604469b51dc46ee98a8c04d0a2054443c14b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Thu, 30 Jul 2020 11:15:51 +0800 Subject: [PATCH 64/93] docs: add _05_replaceSpace --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index a4d8faa..e264aca 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成260道 +- leetcode练习,坚持每天一道,目前已完成261道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -14,7 +14,7 @@ - [x] [数组中重复的数字](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_03_findRepeatNumber.java) - [x] [二维数组中的查找](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_04_findNumberIn2DArray.java) -- [ ] [替换空格](https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof) +- [x] [替换空格](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_05_replaceSpace.java) - [ ] [从尾到头打印链表](https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof) - [ ] [重建二叉树](https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof) - [ ] [用两个栈实现队列](https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof) @@ -53,9 +53,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成260) +### 题目列表(更新中—已完成261) -[Leetcode-Java(260+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_04_findNumberIn2DArray.java) +[Leetcode-Java(260+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_05_replaceSpace.java) #### 剑指offer系列 @@ -63,7 +63,7 @@ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ---- | ---- | | [剑指 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 | | #### 经典题解 @@ -319,7 +319,7 @@ | #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 | 题目 | 解决方案 | 难度 | | ---- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------ | From a06f19ec96c0886980558f706178b23a6b3bb0f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Thu, 30 Jul 2020 11:28:44 +0800 Subject: [PATCH 65/93] feat(EASY): add _06_reversePrint --- src/pp/arithmetic/offer/_06_reversePrint.java | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 src/pp/arithmetic/offer/_06_reversePrint.java 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); + } +} From 589eb8fadbb4216d2058937e193a148bb047a342 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Thu, 30 Jul 2020 11:35:50 +0800 Subject: [PATCH 66/93] docs: add _06_reversePrint --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index e264aca..4b53ec0 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成261道 +- leetcode练习,坚持每天一道,目前已完成262道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -15,7 +15,7 @@ - [x] [数组中重复的数字](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_03_findRepeatNumber.java) - [x] [二维数组中的查找](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_04_findNumberIn2DArray.java) - [x] [替换空格](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_05_replaceSpace.java) -- [ ] [从尾到头打印链表](https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof) +- [x] [从尾到头打印链表]([_06_reversePrint.java](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_06_reversePrint.java)) - [ ] [重建二叉树](https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof) - [ ] [用两个栈实现队列](https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof) - [ ] [斐波那契数列](https://leetcode-cn.com/problems/fei-bo-na-qi-shu-lie-lcof) @@ -53,9 +53,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成261) +### 题目列表(更新中—已完成262) -[Leetcode-Java(260+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_05_replaceSpace.java) +[Leetcode-Java(260+题解,持续更新、欢迎star&留言&交流)]([_06_reversePrint.java](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_06_reversePrint.java)) #### 剑指offer系列 @@ -64,6 +64,7 @@ | [剑指 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 | | #### 经典题解 From 73c680b19c3d2e5c5cc8d3001389021bf42b2caf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Tue, 4 Aug 2020 10:57:28 +0800 Subject: [PATCH 67/93] feat(MEDIUM): add _07_buildTree --- src/pp/arithmetic/offer/_07_buildTree.java | 103 +++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 src/pp/arithmetic/offer/_07_buildTree.java 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; + } + +} From 0ca0a528e55cb7fc252378c60462fc2a7455eaf2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Tue, 4 Aug 2020 10:59:30 +0800 Subject: [PATCH 68/93] docs: add _07_buildTree --- README.md | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 4b53ec0..3bcf95f 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成262道 +- leetcode练习,坚持每天一道,目前已完成263道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -15,8 +15,8 @@ - [x] [数组中重复的数字](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_03_findRepeatNumber.java) - [x] [二维数组中的查找](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_04_findNumberIn2DArray.java) - [x] [替换空格](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_05_replaceSpace.java) -- [x] [从尾到头打印链表]([_06_reversePrint.java](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_06_reversePrint.java)) -- [ ] [重建二叉树](https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof) +- [x] [从尾到头打印链表](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_06_reversePrint.java) +- [x] [重建二叉树](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_07_buildTree.java) - [ ] [用两个栈实现队列](https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof) - [ ] [斐波那契数列](https://leetcode-cn.com/problems/fei-bo-na-qi-shu-lie-lcof) @@ -53,18 +53,19 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成262) +### 题目列表(更新中—已完成263) -[Leetcode-Java(260+题解,持续更新、欢迎star&留言&交流)]([_06_reversePrint.java](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_06_reversePrint.java)) +[Leetcode-Java(260+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_07_buildTree.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 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 | | #### 经典题解 From ab5b84be2f0d257742b1d8541aa3ee3e47014c0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Tue, 4 Aug 2020 17:08:14 +0800 Subject: [PATCH 69/93] feat(EASY): add _09_CQueue --- src/pp/arithmetic/offer/_09_CQueue.java | 118 ++++++++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 src/pp/arithmetic/offer/_09_CQueue.java 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(); + } + } + } +} From ed6c643217344f411ff5d909a744b09af8be9838 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Tue, 4 Aug 2020 17:10:23 +0800 Subject: [PATCH 70/93] docs: add _09_CQueue --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 3bcf95f..30bb0e2 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成263道 +- leetcode练习,坚持每天一道,目前已完成264道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -17,7 +17,7 @@ - [x] [替换空格](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_05_replaceSpace.java) - [x] [从尾到头打印链表](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_06_reversePrint.java) - [x] [重建二叉树](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_07_buildTree.java) -- [ ] [用两个栈实现队列](https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof) +- [x] [用两个栈实现队列](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_09_CQueue.java) - [ ] [斐波那契数列](https://leetcode-cn.com/problems/fei-bo-na-qi-shu-lie-lcof) ## 已解题目 @@ -53,9 +53,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成263) +### 题目列表(更新中—已完成264) -[Leetcode-Java(260+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_07_buildTree.java) +[Leetcode-Java(260+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_09_CQueue.java) #### 剑指offer系列 @@ -66,6 +66,7 @@ | [剑指 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 | | #### 经典题解 From 6b99872a0a4cea66699ea0cf0a91220715c7accd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Tue, 4 Aug 2020 17:34:04 +0800 Subject: [PATCH 71/93] feat(EASY): add _10_fib --- src/pp/arithmetic/offer/_10_fib.java | 65 ++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 src/pp/arithmetic/offer/_10_fib.java 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]; + } +} From 3895fb77bb141fb0fc72dc1df9d99e9560045861 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Tue, 4 Aug 2020 17:44:38 +0800 Subject: [PATCH 72/93] docs: add _10_fib --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 30bb0e2..3b52e59 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成264道 +- leetcode练习,坚持每天一道,目前已完成265道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -18,7 +18,7 @@ - [x] [从尾到头打印链表](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_06_reversePrint.java) - [x] [重建二叉树](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_07_buildTree.java) - [x] [用两个栈实现队列](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_09_CQueue.java) -- [ ] [斐波那契数列](https://leetcode-cn.com/problems/fei-bo-na-qi-shu-lie-lcof) +- [x] [斐波那契数列](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_10_fib.java) ## 已解题目 @@ -53,9 +53,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成264) +### 题目列表(更新中—已完成265) -[Leetcode-Java(260+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_09_CQueue.java) +[Leetcode-Java(260+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_10_fib.java) #### 剑指offer系列 @@ -67,6 +67,7 @@ | [剑指 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 | | #### 经典题解 From a393cd0cee5a707c28f300af6815cea5e2726843 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Wed, 5 Aug 2020 11:05:48 +0800 Subject: [PATCH 73/93] =?UTF-8?q?docs:=20=E6=9B=B4=E6=96=B0=E9=A2=98?= =?UTF-8?q?=E7=9B=AE=E5=88=97=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 3b52e59..adba758 100644 --- a/README.md +++ b/README.md @@ -10,15 +10,21 @@ - 网址:https://leetcode-cn.com/ ## 待解题目列表 -剑指offer系列-持续多月,每周7题 +剑指offer系列-持续多周,每周7题 -- [x] [数组中重复的数字](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_03_findRepeatNumber.java) -- [x] [二维数组中的查找](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_04_findNumberIn2DArray.java) -- [x] [替换空格](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_05_replaceSpace.java) -- [x] [从尾到头打印链表](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_06_reversePrint.java) -- [x] [重建二叉树](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_07_buildTree.java) -- [x] [用两个栈实现队列](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_09_CQueue.java) -- [x] [斐波那契数列](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_10_fib.java) +- [ ] [剑指 Offer 10- II. 青蛙跳台阶问题](https://leetcode-cn.com/problems/qing-wa-tiao-tai-jie-wen-ti-lcof/) + +- [ ] [剑指 Offer 11. 旋转数组的最小数字](https://leetcode-cn.com/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof/) + +- [ ] [剑指 Offer 12. 矩阵中的路径](https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/) + +- [ ] [剑指 Offer 13. 机器人的运动范围](https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/) + +- [ ] [剑指 Offer 14- I. 剪绳子](https://leetcode-cn.com/problems/jian-sheng-zi-lcof/) + +- [ ] [剑指 Offer 14- II. ](https://leetcode-cn.com/problems/jian-sheng-zi-ii-lcof/) + +- [ ] [剑指 Offer 15. 二进制中1的个数](https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/) ## 已解题目 From 7f0fc475823ec1d5756dbab6d85c8735c1db0628 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Wed, 5 Aug 2020 11:57:39 +0800 Subject: [PATCH 74/93] feat(EASY): add _10_2_numWays --- src/pp/arithmetic/offer/_10_2_numWays.java | 65 ++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 src/pp/arithmetic/offer/_10_2_numWays.java 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]; + } +} From ceb914a859ad91dcd347958e42f08b185328c4c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Wed, 5 Aug 2020 11:59:32 +0800 Subject: [PATCH 75/93] docs: add _10_2_numWays --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index adba758..d18e73b 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成265道 +- leetcode练习,坚持每天一道,目前已完成266道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -12,7 +12,7 @@ 剑指offer系列-持续多周,每周7题 -- [ ] [剑指 Offer 10- II. 青蛙跳台阶问题](https://leetcode-cn.com/problems/qing-wa-tiao-tai-jie-wen-ti-lcof/) +- [x] [剑指 Offer 10- II. 青蛙跳台阶问题](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_10_2_numWays.java) - [ ] [剑指 Offer 11. 旋转数组的最小数字](https://leetcode-cn.com/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof/) @@ -59,9 +59,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成265) +### 题目列表(更新中—已完成266) -[Leetcode-Java(260+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_10_fib.java) +[Leetcode-Java(260+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_10_2_numWays.java) #### 剑指offer系列 @@ -74,6 +74,7 @@ | [剑指 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 | | #### 经典题解 From f8e0843ceb81a5b1475a669363eea3b4f676c85a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Wed, 5 Aug 2020 14:57:06 +0800 Subject: [PATCH 76/93] feat(EASY): add _11_minArray --- src/pp/arithmetic/offer/_11_minArray.java | 52 +++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 src/pp/arithmetic/offer/_11_minArray.java 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; + } +} From a11a20cc20430e2ecea6e451cb4a941e457d2373 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Wed, 5 Aug 2020 14:59:24 +0800 Subject: [PATCH 77/93] docs: add _11_minArray --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index d18e73b..cb52d10 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成266道 +- leetcode练习,坚持每天一道,目前已完成267道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -14,7 +14,7 @@ - [x] [剑指 Offer 10- II. 青蛙跳台阶问题](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_10_2_numWays.java) -- [ ] [剑指 Offer 11. 旋转数组的最小数字](https://leetcode-cn.com/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof/) +- [x] [剑指 Offer 11. 旋转数组的最小数字](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_11_minArray.java) - [ ] [剑指 Offer 12. 矩阵中的路径](https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/) @@ -59,9 +59,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成266) +### 题目列表(更新中—已完成267) -[Leetcode-Java(260+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_10_2_numWays.java) +[Leetcode-Java(260+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_11_minArray.java) #### 剑指offer系列 @@ -75,6 +75,7 @@ | [剑指 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 | | #### 经典题解 From 5e8af9e3888e0e44212f51ca0e318e896ff5d405 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Thu, 6 Aug 2020 19:15:38 +0800 Subject: [PATCH 78/93] feat(MEDIUM): add _12_exist --- src/pp/arithmetic/offer/_12_exist.java | 105 +++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 src/pp/arithmetic/offer/_12_exist.java 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; + } + +} From a1231403e5fdd981085c34b11cdf4230ef957ba0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Thu, 6 Aug 2020 19:18:10 +0800 Subject: [PATCH 79/93] docs: add _12_exist --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index cb52d10..5835612 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成267道 +- leetcode练习,坚持每天一道,目前已完成268道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -16,7 +16,7 @@ - [x] [剑指 Offer 11. 旋转数组的最小数字](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_11_minArray.java) -- [ ] [剑指 Offer 12. 矩阵中的路径](https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/) +- [x] [剑指 Offer 12. 矩阵中的路径](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_12_exist.java) - [ ] [剑指 Offer 13. 机器人的运动范围](https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/) @@ -59,9 +59,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成267) +### 题目列表(更新中—已完成268) -[Leetcode-Java(260+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_11_minArray.java) +[Leetcode-Java(260+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_12_exist.java) #### 剑指offer系列 @@ -76,6 +76,7 @@ | [剑指 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 | | #### 经典题解 From 03a5663615bcb270e8d19ce90fb2cb21df72a2af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Fri, 7 Aug 2020 11:03:55 +0800 Subject: [PATCH 80/93] feat(MEDIUM): add _13_movingCount --- src/pp/arithmetic/offer/_13_movingCount.java | 83 ++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 src/pp/arithmetic/offer/_13_movingCount.java 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; + } +} From c37b9e4d135c57a0d4add08b2c951516d3261712 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Fri, 7 Aug 2020 11:06:26 +0800 Subject: [PATCH 81/93] docs: add _13_movingCount --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 5835612..84df919 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成268道 +- leetcode练习,坚持每天一道,目前已完成269道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -18,7 +18,7 @@ - [x] [剑指 Offer 12. 矩阵中的路径](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_12_exist.java) -- [ ] [剑指 Offer 13. 机器人的运动范围](https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/) +- [x] [剑指 Offer 13. 机器人的运动范围](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_13_movingCount.java) - [ ] [剑指 Offer 14- I. 剪绳子](https://leetcode-cn.com/problems/jian-sheng-zi-lcof/) @@ -59,9 +59,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成268) +### 题目列表(更新中—已完成269) -[Leetcode-Java(260+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_12_exist.java) +[Leetcode-Java(260+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_13_movingCount.java) #### 剑指offer系列 @@ -77,6 +77,7 @@ | [剑指 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) | | | | #### 经典题解 From df58bba21a29dfca650cf89b205c6183d94a7cc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Fri, 7 Aug 2020 11:28:06 +0800 Subject: [PATCH 82/93] feat(MEDIUM): add _14_1_cuttingRope --- .../arithmetic/offer/_14_1_cuttingRope.java | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 src/pp/arithmetic/offer/_14_1_cuttingRope.java 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]; + } +} From 34cc44486f8d414a329041a5f4bbe138ec1025ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Fri, 7 Aug 2020 11:33:06 +0800 Subject: [PATCH 83/93] docs: add _14_1_cuttingRope --- README.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 84df919..e9434e3 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成269道 +- leetcode练习,坚持每天一道,目前已完成270道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -20,7 +20,7 @@ - [x] [剑指 Offer 13. 机器人的运动范围](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_13_movingCount.java) -- [ ] [剑指 Offer 14- I. 剪绳子](https://leetcode-cn.com/problems/jian-sheng-zi-lcof/) +- [x] [剑指 Offer 14- I. 剪绳子](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_14_1_cuttingRope.java) - [ ] [剑指 Offer 14- II. ](https://leetcode-cn.com/problems/jian-sheng-zi-ii-lcof/) @@ -59,9 +59,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成269) +### 题目列表(更新中—已完成270) -[Leetcode-Java(260+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_13_movingCount.java) +[Leetcode-Java(270+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_14_1_cuttingRope.java) #### 剑指offer系列 @@ -77,7 +77,8 @@ | [剑指 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) | | | | +| [剑指 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 | | #### 经典题解 From 7db6639a8c87cbebe19520fba8425b2eb3522090 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Mon, 10 Aug 2020 15:30:27 +0800 Subject: [PATCH 84/93] feat(EASY): add _15_hammingWeight --- .../arithmetic/offer/_15_hammingWeight.java | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/pp/arithmetic/offer/_15_hammingWeight.java 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; + } +} From c11e04639757b2b64b3ad7b94d6cfcd3cbb0fbde Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Mon, 10 Aug 2020 15:32:30 +0800 Subject: [PATCH 85/93] docs: add _15_hammingWeight --- README.md | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index e9434e3..64740bd 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成270道 +- leetcode练习,坚持每天一道,目前已完成271道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -22,9 +22,7 @@ - [x] [剑指 Offer 14- I. 剪绳子](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_14_1_cuttingRope.java) -- [ ] [剑指 Offer 14- II. ](https://leetcode-cn.com/problems/jian-sheng-zi-ii-lcof/) - -- [ ] [剑指 Offer 15. 二进制中1的个数](https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/) +- [x] [剑指 Offer 15. 二进制中1的个数](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_15_hammingWeight.java) ## 已解题目 @@ -59,9 +57,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成270) +### 题目列表(更新中—已完成271) -[Leetcode-Java(270+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_14_1_cuttingRope.java) +[Leetcode-Java(270+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_15_hammingWeight.java) #### 剑指offer系列 @@ -79,6 +77,7 @@ | [剑指 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 | | #### 经典题解 From 05c998c0dbd8082da907d0fbe4f42c55e5578785 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Tue, 11 Aug 2020 14:25:20 +0800 Subject: [PATCH 86/93] feat(MEDIUM): add _16_myPow --- src/pp/arithmetic/offer/_16_myPow.java | 71 ++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 src/pp/arithmetic/offer/_16_myPow.java 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; + } + } + +} From 43c49159ed485134a34327a3f8280e52831ab24a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Tue, 11 Aug 2020 14:42:01 +0800 Subject: [PATCH 87/93] docs: add _16_myPow --- README.md | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 64740bd..65204d1 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成271道 +- leetcode练习,坚持每天一道,目前已完成272道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -12,17 +12,19 @@ 剑指offer系列-持续多周,每周7题 -- [x] [剑指 Offer 10- II. 青蛙跳台阶问题](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_10_2_numWays.java) +- [x] [剑指 Offer 16. 数值的整数次方](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_16_myPow.java) -- [x] [剑指 Offer 11. 旋转数组的最小数字](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_11_minArray.java) +- [ ] [剑指 Offer 17. 打印从1到最大的n位数](https://leetcode-cn.com/problems/da-yin-cong-1dao-zui-da-de-nwei-shu-lcof/) -- [x] [剑指 Offer 12. 矩阵中的路径](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_12_exist.java) +- [ ] [剑指 Offer 18. 删除链表的节点](https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/) -- [x] [剑指 Offer 13. 机器人的运动范围](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_13_movingCount.java) +- [ ] [剑指 Offer 19. 正则表达式匹配](https://leetcode-cn.com/problems/zheng-ze-biao-da-shi-pi-pei-lcof/) -- [x] [剑指 Offer 14- I. 剪绳子](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_14_1_cuttingRope.java) +- [ ] [剑指 Offer 20. 表示数值的字符串](https://leetcode-cn.com/problems/biao-shi-shu-zhi-de-zi-fu-chuan-lcof/) -- [x] [剑指 Offer 15. 二进制中1的个数](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_15_hammingWeight.java) +- [ ] [剑指 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/) ## 已解题目 @@ -57,9 +59,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成271) +### 题目列表(更新中—已完成272) -[Leetcode-Java(270+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_15_hammingWeight.java) +[Leetcode-Java(270+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_16_myPow.java) #### 剑指offer系列 @@ -78,6 +80,7 @@ | [剑指 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 | | #### 经典题解 From 5b480122b6a4f89ab7d93ede5fc50111a8e50f57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Tue, 11 Aug 2020 15:05:37 +0800 Subject: [PATCH 88/93] feat(EASY): add _17_printNumbers --- src/pp/arithmetic/offer/_17_printNumbers.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/pp/arithmetic/offer/_17_printNumbers.java 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; + } +} From 0047c51347eb24f0a46578b75b2ccfa78b0b0fdc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Tue, 11 Aug 2020 15:08:07 +0800 Subject: [PATCH 89/93] docs: add _17_printNumbers --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 65204d1..e208566 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成272道 +- leetcode练习,坚持每天一道,目前已完成273道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -14,7 +14,7 @@ - [x] [剑指 Offer 16. 数值的整数次方](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_16_myPow.java) -- [ ] [剑指 Offer 17. 打印从1到最大的n位数](https://leetcode-cn.com/problems/da-yin-cong-1dao-zui-da-de-nwei-shu-lcof/) +- [x] [剑指 Offer 17. 打印从1到最大的n位数](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_17_printNumbers.java) - [ ] [剑指 Offer 18. 删除链表的节点](https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/) @@ -59,9 +59,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成272) +### 题目列表(更新中—已完成273) -[Leetcode-Java(270+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_16_myPow.java) +[Leetcode-Java(270+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_17_printNumbers.java) #### 剑指offer系列 @@ -81,6 +81,7 @@ | [剑指 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 | | #### 经典题解 From 8a8b2773edef2aaeb4f1f734a1d2a280363372af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Wed, 2 Sep 2020 10:10:49 +0800 Subject: [PATCH 90/93] feat(EASY): add _6_minCount --- src/pp/arithmetic/LCP/_6_minCount.java | 62 ++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/pp/arithmetic/LCP/_6_minCount.java 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; + } +} From 465faf2f36f02d5a41ec2051af571afa9f984aa9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Wed, 2 Sep 2020 10:13:24 +0800 Subject: [PATCH 91/93] docs: add _6_minCount --- README.md | 41 ++++++++++++++++++++--------------------- 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index e208566..d845c17 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成273道 +- leetcode练习,坚持每天一道,目前已完成274道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -12,19 +12,17 @@ 剑指offer系列-持续多周,每周7题 -- [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) - -- [ ] [剑指 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/) +- [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) +- [ ] [剑指 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/) -- [ ] [剑指 Offer 21. 调整数组顺序使奇数位于偶数前面](https://leetcode-cn.com/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof/) +LCP -- [ ] [剑指 Offer 22. 链表中倒数第k个节点](https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/) +- [x] [LCP 06. 拿硬币](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/LCP/_6_minCount.java) ## 已解题目 @@ -59,9 +57,9 @@ - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成273) +### 题目列表(更新中—已完成274) -[Leetcode-Java(270+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_17_printNumbers.java) +[Leetcode-Java(270+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/LCP/_6_minCount.java) #### 剑指offer系列 @@ -339,11 +337,12 @@ #### 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 | | From e800773f58190bdd6c5fad857eb1fc6a0705b884 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Wed, 9 Sep 2020 11:48:57 +0800 Subject: [PATCH 92/93] feat(EASY): add _18_deleteNode --- src/pp/arithmetic/offer/_18_deleteNode.java | 74 +++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 src/pp/arithmetic/offer/_18_deleteNode.java 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; + } +} From f1b3876b2f3de7c06c17a6a2a6d483541d1af514 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=B9=8F?= Date: Wed, 9 Sep 2020 11:51:30 +0800 Subject: [PATCH 93/93] docs: add _18_deleteNode --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index d845c17..a008d61 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode-Java ## 说明 -- leetcode练习,坚持每天一道,目前已完成274道 +- leetcode练习,坚持每天一道,目前已完成275道 - 解题语言是Java - 每道题都是可编译运行的 - 每道题有自己的方法和他人优秀解法 @@ -14,7 +14,7 @@ - [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) -- [ ] [剑指 Offer 18. 删除链表的节点](https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/) +- [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/) @@ -57,9 +57,9 @@ LCP - [线段树](https://leetcode-cn.com/tag/segment-tree/)(9) - [二叉搜索树](https://leetcode-cn.com/tag/binary-search-tree/)(15) -### 题目列表(更新中—已完成274) +### 题目列表(更新中—已完成275) -[Leetcode-Java(270+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/LCP/_6_minCount.java) +[Leetcode-Java(270+题解,持续更新、欢迎star&留言&交流)](https://github.com/pphdsny/Leetcode-Java/blob/master/src/pp/arithmetic/offer/_18_deleteNode.java) #### 剑指offer系列 @@ -80,6 +80,7 @@ LCP | [剑指 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 | | #### 经典题解