Minimum Number Game

easy array sorting simulation

Problem

You are given a 0-indexed integer array nums of even length. Alice and Bob play rounds: each round, Alice first removes the minimum element from nums, then Bob removes the minimum from what remains. Bob appends his removed number to the result array arr first, then Alice appends hers. Repeat until nums is empty, and return arr.

Inputnums = [5,4,2,3]
Output[3,2,5,4]
Round 1: Alice takes 2, Bob takes 3; Bob appends 3 then Alice 2. Round 2: Alice 4, Bob 5; append 5 then 4.

def number_game(nums):
    nums.sort()
    arr = []
    for i in range(0, len(nums), 2):
        alice = nums[i]
        bob = nums[i + 1]
        arr.append(bob)
        arr.append(alice)
    return arr
function numberGame(nums) {
  nums.sort((a, b) => a - b);
  const arr = [];
  for (let i = 0; i < nums.length; i += 2) {
    const alice = nums[i];
    const bob = nums[i + 1];
    arr.push(bob);
    arr.push(alice);
  }
  return arr;
}
class Solution {
    public int[] numberGame(int[] nums) {
        Arrays.sort(nums);
        int[] arr = new int[nums.length];
        for (int i = 0; i < nums.length; i += 2) {
            arr[i] = nums[i + 1];
            arr[i + 1] = nums[i];
        }
        return arr;
    }
}
vector<int> numberGame(vector<int>& nums) {
    sort(nums.begin(), nums.end());
    vector<int> arr(nums.size());
    for (int i = 0; i < (int)nums.size(); i += 2) {
        arr[i] = nums[i + 1];
        arr[i + 1] = nums[i];
    }
    return arr;
}
Time: O(n log n) Space: O(n)