LC剑指 Offer 31. 栈的压入、弹出序列
//模拟一个栈的压入和弹出的一个过程,用一个指针指向出栈的下标,如果栈顶元素和出栈序列相同那么久弹栈即可,最后判断栈是否为空
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Deque<Integer> stack = new LinkedList();
int i = 0;
for(int num : pushed){
stack.push(num);
while(!stack.isEmpty() && stack.peek() == popped[i]){
stack.pop();
i++;
}
}
return stack.isEmpty();
}
}
LC剑指 Offer 12. 矩阵中的路径
//有点像岛屿路径问题,在二维数组当中查找一条合适的路径,固定的模板。
class Solution {
public boolean exist(char[][] board, String word) {
char[] warr = word.toCharArray();
for(int i = 0;i < board.length;i++){
for(int j = 0;j < board[0].length;j++){
if(dfs(board,i,j,0,warr)) return true;
}
}
return false;
}
public boolean dfs(char[][] board,int i,int j,int k,char[] word){
if(i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != word[k])
return false;
if(k == word.length - 1) return true;
board[i][j] = '\0';
boolean res = dfs(board,i,j - 1,k + 1,word) || dfs(board,i - 1,j,k + 1,word) ||
dfs(board,i,j + 1,k + 1,word) || dfs(board,i + 1,j,k + 1,word);
board[i][j] = word[k];
return res;
}
}
LC703. 数据流中的第 K 大元素
//编写一个类存放数据流当中第K大的元素,其实也就是利用优先队列,存放前k个的元素那么头部就是第K大的元素
class KthLargest {
PriorityQueue<Integer> queue;
int k;
public KthLargest(int k, int[] nums) {
this.k = k;
queue = new PriorityQueue();
for(int num : nums){
add(num);
}
}
public int add(int val) {
queue.offer(val);
if(queue.size() > k){
queue.poll();
}
return queue.peek();
}
}
/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest obj = new KthLargest(k, nums);
* int param_1 = obj.add(val);
*/