You are given a 0-indexed integer array nums of even length and there is also an empty array arr. Alice and Bob decided to play a game where in every round Alice and Bob will do one move. The rules of the game are as follows:
Every round, first Alice will remove the minimum element from nums, and then Bob does the same.
Now, first Bob will append the removed element in the array arr, and then Alice does the same.
Input: nums =[5,4,2,3]Output: [3,2,5,4]Explanation: In round one, first Alice removes 2 and then Bob removes 3. Then in arr firstly Bob appends 3 and then Alice appends 2. So arr =[3,2].At the begining of round two, nums =[5,4]. Now, first Alice removes 4 and then Bob removes 5. Then both append in arr which becomes [3,2,5,4].
Input: nums =[2,5]Output: [5,2]Explanation: In round one, first Alice removes 2 and then Bob removes 5. Then in arr firstly Bob appends and then Alice appends. So arr =[5,2].
Since Alice and Bob always pick the minimum elements, sorting the array allows us to simulate the game efficiently. Bob always appends his pick first, then Alice, so we alternate appending from the sorted array.
classSolution {
publicint[]numberGame(int[] nums) {
Arrays.sort(nums);
int[] ans =newint[nums.length];
int idx = 0;
for (int i = 0; i < nums.length; i += 2) {
ans[idx++]= nums[i+1];
ans[idx++]= nums[i];
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funnumberGame(nums: IntArray): IntArray {
nums.sort()
val ans = IntArray(nums.size)
var idx = 0for (i in nums.indices step 2) {
ans[idx++] = nums[i+1]
ans[idx++] = nums[i]
}
return ans
}
}
1
2
3
4
5
6
7
8
classSolution:
defnumberGame(self, nums: list[int]) -> list[int]:
nums.sort()
ans: list[int] = []
for i in range(0, len(nums), 2):
ans.append(nums[i+1])
ans.append(nums[i])
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfnnumber_game(mut nums: Vec<i32>) -> Vec<i32> {
nums.sort();
letmut ans = Vec::with_capacity(nums.len());
let n = nums.len();
letmut i =0;
while i < n {
ans.push(nums[i+1]);
ans.push(nums[i]);
i +=2;
}
ans
}
}