diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index f6cfad29..6ac97af1 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -140,6 +140,11 @@ class Solution { for (int i = 0; i < nums.length; i++) { + // nums[i] > target 直接返回, 剪枝操作 + if (nums[i] > 0 && nums[i] > target) { + return result; + } + if (i > 0 && nums[i - 1] == nums[i]) { continue; } diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index ed27f95d..55980189 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -294,14 +294,13 @@ class solution { /** * 递归法 */ - public int maxdepth(treenode root) { + public int maxDepth(TreeNode root) { if (root == null) { return 0; } - int leftdepth = maxdepth(root.left); - int rightdepth = maxdepth(root.right); - return math.max(leftdepth, rightdepth) + 1; - + int leftDepth = maxDepth(root.left); + int rightDepth = maxDepth(root.right); + return Math.max(leftDepth, rightDepth) + 1; } } ``` @@ -311,23 +310,23 @@ class solution { /** * 迭代法,使用层序遍历 */ - public int maxdepth(treenode root) { + public int maxDepth(TreeNode root) { if(root == null) { return 0; } - deque deque = new linkedlist<>(); + Deque deque = new LinkedList<>(); deque.offer(root); int depth = 0; - while (!deque.isempty()) { + while (!deque.isEmpty()) { int size = deque.size(); depth++; for (int i = 0; i < size; i++) { - treenode poll = deque.poll(); - if (poll.left != null) { - deque.offer(poll.left); + TreeNode node = deque.poll(); + if (node.left != null) { + deque.offer(node.left); } - if (poll.right != null) { - deque.offer(poll.right); + if (node.right != null) { + deque.offer(node.right); } } } diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index a04041cc..0c978b2a 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -141,13 +141,10 @@ class Solution { } Set> entries = map.entrySet(); - // 根据map的value值正序排,相当于一个小顶堆 - PriorityQueue> queue = new PriorityQueue<>((o1, o2) -> o1.getValue() - o2.getValue()); + // 根据map的value值,构建于一个大顶堆(o1 - o2: 小顶堆, o2 - o1 : 大顶堆) + PriorityQueue> queue = new PriorityQueue<>((o1, o2) -> o2.getValue() - o1.getValue()); for (Map.Entry entry : entries) { queue.offer(entry); - if (queue.size() > k) { - queue.poll(); - } } for (int i = k - 1; i >= 0; i--) { result[i] = queue.poll().getKey(); diff --git a/problems/0977.有序数组的平方.md b/problems/0977.有序数组的平方.md index 458107dd..59816eb3 100644 --- a/problems/0977.有序数组的平方.md +++ b/problems/0977.有序数组的平方.md @@ -106,6 +106,7 @@ class Solution { int index = result.length - 1; while (left <= right) { if (nums[left] * nums[left] > nums[right] * nums[right]) { + // 正数的相对位置是不变的, 需要调整的是负数平方后的相对位置 result[index--] = nums[left] * nums[left]; ++left; } else {