diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index 64923e41..fb8557fa 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -35,7 +35,7 @@ 四数之和,和[15.三数之和](https://programmercarl.com/0015.三数之和.html)是一个思路,都是使用双指针法, 基本解法就是在[15.三数之和](https://programmercarl.com/0015.三数之和.html) 的基础上再套一层for循环。 -但是有一些细节需要注意,例如: 不要判断`nums[k] > target` 就返回了,三数之和 可以通过 `nums[i] > 0` 就返回了,因为 0 已经是确定的数了,四数之和这道题目 target是任意值。比如:数组是`[-4, -3, -2, -1]`,`target`是`-10`,不能因为`-4 > -10`而跳过。但是我们依旧可以去做剪枝,逻辑变成`nums[i] > target && (nums[i] >=0 || target >= 0)`就可以了。 +但是有一些细节需要注意,例如: 不要判断`nums[k] > target` 就返回了,三数之和 可以通过 `nums[i] > 0` 就返回了,因为 0 已经是确定的数了,四数之和这道题目 target是任意值。比如:数组是`[-4, -3, -2, -1]`,`target`是`-10`,不能因为`-4 > -10`而跳过。但是我们依旧可以去做剪枝,逻辑变成`nums[k] > target && (nums[k] >=0 || target >= 0)`就可以了。 [15.三数之和](https://programmercarl.com/0015.三数之和.html)的双指针解法是一层for循环num[i]为确定值,然后循环内有left和right下标作为双指针,找到nums[i] + nums[left] + nums[right] == 0。 @@ -802,3 +802,4 @@ end + diff --git a/problems/0020.有效的括号.md b/problems/0020.有效的括号.md index f2f5cdd1..493e2871 100644 --- a/problems/0020.有效的括号.md +++ b/problems/0020.有效的括号.md @@ -172,6 +172,29 @@ class Solution { } ``` +```java +// 解法二 +// 对应的另一半一定在栈顶 +class Solution { + public boolean isValid(String s) { + Stack stack = new Stack<>(); + for(char c : s.toCharArray()){ + // 有对应的另一半就直接消消乐 + if(c == ')' && !stack.isEmpty() && stack.peek() == '(') + stack.pop(); + else if(c == '}' && !stack.isEmpty() && stack.peek() == '{') + stack.pop(); + else if(c == ']' && !stack.isEmpty() && stack.peek() == '[') + stack.pop(); + else + stack.push(c);// 没有匹配的就放进去 + } + + return stack.isEmpty(); + } +} +``` + ### Python: ```python diff --git a/problems/0239.滑动窗口最大值.md b/problems/0239.滑动窗口最大值.md index 9bb3494d..651e4da4 100644 --- a/problems/0239.滑动窗口最大值.md +++ b/problems/0239.滑动窗口最大值.md @@ -267,7 +267,7 @@ class Solution { //利用双端队列手动实现单调队列 /** * 用一个单调队列来存储对应的下标,每当窗口滑动的时候,直接取队列的头部指针对应的值放入结果集即可 - * 单调队列类似 (tail -->) 3 --> 2 --> 1 --> 0 (--> head) (右边为头结点,元素存的是下标) + * 单调递减队列类似 (head -->) 3 --> 2 --> 1 --> 0 (--> tail) (左边为头结点,元素存的是下标) */ class Solution { public int[] maxSlidingWindow(int[] nums, int k) { @@ -281,7 +281,7 @@ class Solution { while(!deque.isEmpty() && deque.peek() < i - k + 1){ deque.poll(); } - // 2.既然是单调,就要保证每次放进去的数字要比末尾的都大,否则也弹出 + // 2.维护单调递减队列:新元素若大于队尾元素,则弹出队尾元素,直到满足单调性 while(!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) { deque.pollLast(); } @@ -926,3 +926,4 @@ int* maxSlidingWindow(int* nums, int numsSize, int k, int* returnSize) { +