用栈实现队列
-
情景:使用栈实现队列
-
实现思路:(2023/09/03午)
-
利用栈先进后出的特性,首先一个栈inStack将元素压栈,它负责 “进” 元素
-
inStack再依次出栈,另一个栈outStack负责将出栈的元素压栈,它负责 “出” 元素
-
-
具体代码如下:
/**
* 用栈实现队列
*/
class MyQueue {
Deque<Integer> inStack;
Deque<Integer> outStack;
public MyQueue() {
inStack = new LinkedList<Integer>();
outStack = new LinkedList<Integer>();
}
public void push(int x) {
inStack.push(x);
}
public int pop() {
if (outStack.isEmpty()) {
in2out();
}
return outStack.pop();
}
public int peek() {
if (outStack.isEmpty()) {
in2out();
}
return outStack.peek();
}
public boolean empty() {
return inStack.isEmpty() && outStack.isEmpty();
}
private void in2out() {
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
}
}
用队列实现栈
-
实现思路:(2023/09/03午)
-
用两个队列实现栈可以这样做:假设你有队列A和队列B,每次push一个元素,都放入队列A中
-
当你想要pop一个元素时,先将队列A中的元素依次出队并入队到队列B中,直到队列A中只剩下一个元素,然后将这个元素出队
-
这样,你就模拟了栈后进先出的特性
-
当你继续执行push操作时,将元素放入非空的队列(此时是队列A)
-
而当你想要pop操作时,将除队列A中最后一个元素外的所有元素从队列A出队并依次入队到队列B中,再将队列A中剩下的最后一个元素出队
-
这样,可以保持栈的后进先出的特性,并且实现了用两个队列来模拟栈的功能
-
需要注意的是,每次pop操作后,需要交换队列A和队列B的角色,以便下一次的操作
-
-
具体代码如下:
/**
* 用队列实现栈
*/
class MyStack {
Queue<Integer> queue1;
Queue<Integer> queue2;
public MyStack() {
queue1 = new LinkedList<Integer>();
queue2 = new LinkedList<Integer>();
}
public void push(int x) {
queue2.offer(x);
while (!queue1.isEmpty()) {
queue2.offer(queue1.poll());
}
Queue<Integer> temp = queue1;
queue1 = queue2;
queue2 = temp;
}
public int pop() {
return queue1.poll();
}
public int top() {
return queue1.peek();
}
public boolean empty() {
return queue1.isEmpty();
}
}
两数之和
-
这题我之前做过,力扣里为数不多做过的题
-
情景:
输入:nums = [2,7,11,15], target = 9 输出:[0,1] 解释:2 + 7 = 9, 返回二者下标
-
解决思路有三种,这里统一讲:
-
遍历数组,依次拿到 i 和 i +1 相加,判断是否等于 target。缺点:双层循环嵌套 ---> 时间复杂度大
-
建立一张Hash表,存储 target - x,存在即返回,不存在即存储 x,继续遍历 ---> 遍历过的数字已经存储到map中了,减少了遍历元素的个数
-
排序数组,将二层循环改为二分查找
-
-
具体代码如下:
public static int[] twoSum(int[] nums, int target) {
int n = nums.length;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
return new int[0];
}
public int[] twoSum3(int[] nums, int target) {
// 数组元素值 -> 对应下标
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
return new int[]{i, map.get(target - nums[i])};
}
map.put(nums[i], i);
}
return new int[0];
}