Merge pull request #432 from KailokFung/master

fix(1047): 新增双指针java写法;使用ArrayDeque
This commit is contained in:
程序员Carl
2021-06-24 15:19:01 +08:00
committed by GitHub
2 changed files with 61 additions and 1 deletions

View File

@ -208,6 +208,7 @@ public:
Java
```Java
//解法一
//自定义数组
class MyQueue {
Deque<Integer> deque = new LinkedList<>();
@ -260,6 +261,40 @@ class Solution {
return res;
}
}
//解法二
//利用双端队列手动实现单调队列
/**
* 用一个单调队列来存储对应的下标,每当窗口滑动的时候,直接取队列的头部指针对应的值放入结果集即可
* 单调队列类似 tail --> 3 --> 2 --> 1 --> 0 (--> head) (右边为头结点,元素存的是下标)
*/
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
ArrayDeque<Integer> deque = new ArrayDeque<>();
int n = nums.length;
int[] res = new int[n - k + 1];
int idx = 0;
for(int i = 0; i < n; i++) {
// 根据题意i为nums下标是要在[i - k + 1, k] 中选到最大值,只需要保证两点
// 1.队列头结点需要在[i - k + 1, k]范围内,不符合则要弹出
while(!deque.isEmpty() && deque.peek() < i - k + 1){
deque.poll();
}
// 2.既然是单调,就要保证每次放进去的数字要比末尾的都大,否则也弹出
while(!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) {
deque.pollLast();
}
deque.offer(i);
// 因为单调当i增长到符合第一个k范围的时候每滑动一步都将队列头节点放入结果就行了
if(i >= k - 1){
res[idx++] = nums[deque.peek()];
}
}
return res;
}
}
```
Python

View File

@ -127,7 +127,9 @@ Java
```Java
class Solution {
public String removeDuplicates(String S) {
Deque<Character> deque = new LinkedList<>();
//ArrayDeque会比LinkedList在除了删除元素这一点外会快一点
//参考https://stackoverflow.com/questions/6163166/why-is-arraydeque-better-than-linkedlist
ArrayDeque<Character> deque = new ArrayDeque<>();
char ch;
for (int i = 0; i < S.length(); i++) {
ch = S.charAt(i);
@ -171,6 +173,29 @@ class Solution {
}
```
拓展:双指针
```java
class Solution {
public String removeDuplicates(String s) {
char[] ch = s.toCharArray();
int fast = 0;
int slow = 0;
while(fast < s.length()){
// 直接用fast指针覆盖slow指针的值
ch[slow] = ch[fast];
// 遇到前后相同值的就跳过即slow指针后退一步下次循环就可以直接被覆盖掉了
if(slow > 0 && ch[slow] == ch[slow - 1]){
slow--;
}else{
slow++;
}
fast++;
}
return new String(ch,0,slow);
}
}
```
Python
```python3
class Solution: