Re: [閒聊] 每日LeetCode

作者: Rushia (みけねこ的鼻屎)   2023-11-03 23:21:09
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:

Links booklink

Contact Us: admin [ a t ] ucptt.com