https://leetcode.com/problems/build-an-array-with-stack-operations/description
1441. Build an Array With Stack Operations
給你一個陣列 target[] 和一個數字 n ,n 表示一個範圍 1~n 的連續數字資料流,
我們可以對這個資料流做兩個操作:
1.PUSH:從資料流取出一個資料放入結果集頂端,若取出 i 下次會 PUSH 出 i + 1。
2.POP:從結果集POP(移除頂端)一個資料。
求出要用什麼樣的順序對結果集PUSH和POP可以得到TARGET。
* 題目保證一定存在至少一個合法的PUSH和POP順序,若有多種可能只需返回其中一種。
* 結果集初始化為 []
Example 1:
Input: target = [1,3], n = 3
Output: ["Push","Push","Pop","Push"]
Explanation: Initially the stack s is empty. The last element is the top of
the stack.
Read 1 from the stream and push it to the stack. s = [1].
Read 2 from the stream and push it to the stack. s = [1,2].
Pop the integer on the top of the stack. s = [1].
Read 3 from the stream and push it to the stack. s = [1,3].
思路:
1.有Stack的觀念然後就可以用雙指針處理,每次固定從流PUSH一個元素到結果集。
2.如果頂端元素和target的當前元素相同,繼續往後面匹配(移動指針),否則Pop
掉剛剛Push的元素。
3.上面的PUSH和POP過程保存起來,做到指標走完target就可以結束(後面的流不用管)
Java Code:
-------------------------------------------------
class Solution {
public List<String> buildArray(int[] target, int n) {
List<String> res = new ArrayList<>();
int curr = 1;
int i = 0;
while (i < target.length) {
res.add("Push");
if (curr == target[i]) {
i++;
} else {
res.add("Pop");
}
curr++;
}
return res;
}
}
-------------------------------------------------
姆咪
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.73.13 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1699024871.A.F61.html
※ 編輯: Rushia (122.100.73.13 臺灣), 11/03/2023 23:22:15
※ 編輯: Rushia (122.100.73.13 臺灣), 11/03/2023 23:23:07