使用佇列實作堆疊
來源:Hackernoon 本文的內容致力於解決僅使用兩個佇列實作堆疊的問題。 我們在 Leetcode 中遇到了一個問題:
僅使用兩個佇列實作後進先出 (LIFO) 堆疊。實作的堆疊必須支援常規堆疊的所有功能(push、top、pop和empty)。 實作 MyStack 類別:
額外細節:
範例1: 輸入
輸出
[空、空、空、2、2、假]
解釋
|
問題的解決
第一個選項
在第一個解決方案中,我們將使用額外的記憶體:static class MyStack {
private Queue<Integer> current;
private Queue<Integer> tmp;
public MyStack() {
current = new ArrayDeque<>();
tmp = new ArrayDeque<>();
}
對於這個解決方案,我們需要一個額外的隊列。讓我們從推送開始。對於推送操作,我們只需將一個新元素新增至目前佇列即可。
public void push(int x) {
current.add(x);
}
這裡的主要技巧是pop方法。這裡我們將除最後一個之外的所有元素放入tmp隊列中。 現在佇列中的最後一個元素成為第一個發送的元素。
public int pop() {
if (current.isEmpty()){
return -1;
}
int size = current.size();
for (int i = 0; i < size - 1; i ++){
tmp.add(current.poll());
}
int ret = current.poll();
current = tmp;
return ret;
}
上面的方法 怎麼樣?此方法類似於pop:
public int top() {
if (current.isEmpty()){
return -1;
}
int size = current.size();
for (int i = 0; i < size - 1; i ++){
tmp.add(current.poll());
}
int ret = current.peek();
tmp.add(current.poll());
current = tmp;
return ret;
}
對於最後一個空方法,我們應該簡單地檢查當前隊列:
public boolean empty() {
return current.isEmpty();
}
第二種解決方案
在此選項中,我們不會使用額外的記憶體:static class MyStack {
private Queue<Integer> current;
public MyStack2() {
current = new ArrayDeque<>();
}
}
這裡的主要思想是push方法。我們新增目前元素,然後將目前元素之前的元素移到佇列末尾。例如,如果我們有一個包含元素[2,1]的隊列,我們使用push 3 - 並取得隊列[3,2,1],然後是[1,3,2],[2,1,3 ]和。 .. 和所有。
public void push(int x) {
current.add(x);
int size = current.size();
for (int i = 0; i < size-1; i ++){
current.add(current.poll());
}
}
在這裡,我們已經擁有了所有其他方法的正確元素和佇列的開頭。
public int pop() {
return current.poll();
}
public int top() {
return current.peek();
}
public boolean empty() {
return current.isEmpty();
}
Java Math 類別方法
來源:Medium 在這篇文章中,您將了解 Java Math 類別的功能和範圍。 Java 語言中Java.lang.Math套件的一部分是Math類別。這個類別為我們提供了一些預先定義的方法,如min、max、sqrt等。以下是我們可以在日常工作中使用的數學課程中的一些方法的範例。1. max()方法傳回參數中傳遞的較大數字:System.out.println(Math.max(5,3));
OUTPUT: 5
2. sqrt()方法將向我們顯示作為參數傳遞的數字的平方根:
System.out.println(Math.sqrt(4));
OUTPUT: 2.0
3. random()方法傳回0到1範圍內的隨機數。
System.out.println(Math.random());
OUTPUT: 0.8685304957692445
4. abs()方法傳回任何負數的絕對正值。例如,如果我們將其傳遞為 0,則結果將傳回 0。
System.out.println(Math.abs(-4));
OUTPUT: 4
System.out.println(Math.abs(4));
OUTPUT: 4
System.out.println(Math.abs(0));
OUTPUT: 0
5.floor () 方法傳回一個小於或等於參數且等於最接近的數學整數的雙精度值。
System.out.println(Math.floor(-1.2));
OUTPUT: -2.0
System.out.println(Math.floor(1.2));
OUTPUT: 2.0
GO TO FULL VERSION