@@ -43,30 +43,119 @@ At the begining of round two, nums = [5,4]. Now, first Alice removes 4 and then
43
43
44
44
## Solutions
45
45
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
+
46
52
<!-- tabs:start -->
47
53
48
54
### ** Python3**
49
55
50
56
``` 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
52
66
```
53
67
54
68
### ** Java**
55
69
56
70
``` 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
+ }
58
87
```
59
88
60
89
### ** C++**
61
90
62
91
``` 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
+ };
64
111
```
65
112
66
113
### **Go**
67
114
68
115
```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
+ ```
69
142
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
+ }
70
159
```
71
160
72
161
### ** ...**
0 commit comments