@@ -43,30 +43,119 @@ At the begining of round two, nums = [5,4]. Now, first Alice removes 4 and then
4343
4444## Solutions
4545
46+ ** Solution 1: Simulation + Priority Queue (Min Heap)**
47+
48+ We can put the elements in the array $nums$ into a min heap one by one, and each time take out two elements $a$ and $b$ from the min heap, then put $b$ and $a$ into the answer array in turn, until the min heap is empty.
49+
50+ Time complexity is $O(n \times \log n)$, and space complexity is $O(n)$. Where $n$ is the length of the array $nums$.
51+
4652<!-- tabs:start -->
4753
4854### ** Python3**
4955
5056``` python
51-
57+ class Solution :
58+ def numberGame (self , nums : List[int ]) -> List[int ]:
59+ heapify(nums)
60+ ans = []
61+ while nums:
62+ a, b = heappop(nums), heappop(nums)
63+ ans.append(b)
64+ ans.append(a)
65+ return ans
5266```
5367
5468### ** Java**
5569
5670``` java
57-
71+ class Solution {
72+ public int [] numberGame (int [] nums ) {
73+ PriorityQueue<Integer > pq = new PriorityQueue<> ();
74+ for (int x : nums) {
75+ pq. offer(x);
76+ }
77+ int [] ans = new int [nums. length];
78+ int i = 0 ;
79+ while (! pq. isEmpty()) {
80+ int a = pq. poll();
81+ ans[i++ ] = pq. poll();
82+ ans[i++ ] = a;
83+ }
84+ return ans;
85+ }
86+ }
5887```
5988
6089### ** C++**
6190
6291``` cpp
63-
92+ class Solution {
93+ public:
94+ vector<int > numberGame(vector<int >& nums) {
95+ priority_queue<int, vector<int >, greater<int >> pq;
96+ for (int x : nums) {
97+ pq.push(x);
98+ }
99+ vector<int > ans;
100+ while (pq.size()) {
101+ int a = pq.top();
102+ pq.pop();
103+ int b = pq.top();
104+ pq.pop();
105+ ans.push_back(b);
106+ ans.push_back(a);
107+ }
108+ return ans;
109+ }
110+ };
64111```
65112
66113### **Go**
67114
68115```go
116+ func numberGame(nums []int) (ans []int) {
117+ pq := &hp{nums}
118+ heap.Init(pq)
119+ for pq.Len() > 0 {
120+ a := heap.Pop(pq).(int)
121+ b := heap.Pop(pq).(int)
122+ ans = append(ans, b)
123+ ans = append(ans, a)
124+ }
125+ return
126+ }
127+
128+ type hp struct{ sort.IntSlice }
129+
130+ func (h *hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] }
131+ func (h *hp) Pop() interface{} {
132+ old := h.IntSlice
133+ n := len(old)
134+ x := old[n-1]
135+ h.IntSlice = old[0 : n-1]
136+ return x
137+ }
138+ func (h *hp) Push(x interface{}) {
139+ h.IntSlice = append(h.IntSlice, x.(int))
140+ }
141+ ```
69142
143+ ### ** TypeScript**
144+
145+ ``` ts
146+ function numberGame(nums : number []): number [] {
147+ const pq = new MinPriorityQueue ();
148+ for (const x of nums ) {
149+ pq .enqueue (x );
150+ }
151+ const ans: number [] = [];
152+ while (pq .size ()) {
153+ const a = pq .dequeue ().element ;
154+ const b = pq .dequeue ().element ;
155+ ans .push (b , a );
156+ }
157+ return ans ;
158+ }
70159```
71160
72161### ** ...**
0 commit comments