#2610

Convert an Array Into a 2D Array With Conditions

pupil · 385 · lc medium +24 · verified · 86.4% accepted · 1,691 likes · top 97%

Description

You are given an integer array nums. Arrange all elements into a 2D array where each row contains only distinct integers and the number of rows is minimized. Rows may have different lengths. Return any valid result.

Example 1:

Input: nums = [1,3,4,1,2,3,1]
Output: [[1,3,4,2],[1,3],[1]]
Explanation: We can create a 2D array that contains the following rows:
- 1,3,4,2
- 1,3
- 1
All elements of nums were used, and each row of the 2D array contains distinct integers, so it is a valid answer.
It can be shown that we cannot have less than 3 rows in a valid array.

Example 2:

Input: nums = [1,2,3,4]
Output: [[4,3,2,1]]
Explanation: All elements of the array are distinct, so we can keep all of them in the first row of the 2D array.

Code

1
2
3