Loading

LeetCode problem#2974

Minimum Number Game

Solved in 1 languageJava

Solve it on LeetCode(opens in a new tab)

Solution

36 lines
1import java.util.Arrays;
2// import java.util.PriorityQueue;
3
4class Solution {
5    // without new array, modifying in place
6    public int[] numberGame(int[] nums) {
7        Arrays.sort(nums);
8
9        for (int i = 1; i < nums.length; i += 2) {
10            int temp = nums[i];
11            nums[i] = nums[i - 1];
12            nums[i - 1] = temp;
13        }
14
15        return nums;
16    }
17
18    // public int[] numberGame(int[] nums) {
19    //     // Minheap with capacity passed to constructor
20    //     PriorityQueue<Integer> pq = new PriorityQueue<Integer>(nums.length);
21    //     int[] arr = new int[nums.length];
22
23    //     for (int i = 0; i < nums.length; i++) {
24    //         pq.add(nums[i]);
25    //     }
26
27    //     for (int i = 1; i < arr.length; i += 2) {
28    //         int first = pq.poll();
29    //         int second = pq.poll();
30    //         arr[i - 1] = second;
31    //         arr[i] = first;
32    //     }
33
34    //     return arr;
35    // }
36}

Want a walkthrough of this Java solution?

Get a step-by-step explanation of the idea behind the code.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.