Merge pull request #2867 from JianWangUCD/jian

更新20有效的括号 Java更简单易懂的新解法、18四数之和 修改思路第二段末尾描述、修改239滑动窗口最大值java代码注释严重错误
This commit is contained in:
程序员Carl
2025-01-17 19:59:57 +08:00
committed by GitHub
3 changed files with 28 additions and 3 deletions

View File

@ -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
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

View File

@ -172,6 +172,29 @@ class Solution {
}
```
```java
// 解法二
// 对应的另一半一定在栈顶
class Solution {
public boolean isValid(String s) {
Stack<Character> 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

View File

@ -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) {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>