Merge branch 'youngyangyang04:master' into master

This commit is contained in:
HJF
2025-01-20 22:54:37 +08:00
committed by GitHub
4 changed files with 57 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。

View File

@ -129,6 +129,36 @@ class Solution {
}
```
```java
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
// 创建一个新的哑节点,指向原链表头
ListNode s = new ListNode(-1, head);
// 递归调用remove方法从哑节点开始进行删除操作
remove(s, n);
// 返回新链表的头(去掉可能的哑节点)
return s.next;
}
public int remove(ListNode p, int n) {
// 递归结束条件如果当前节点为空返回0
if (p == null) {
return 0;
}
// 递归深入到下一个节点
int net = remove(p.next, n);
// 如果当前节点是倒数第n个节点进行删除操作
if (net == n) {
p.next = p.next.next;
}
// 返回当前节点的总深度
return net + 1;
}
}
```
### Python:
```python

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>