Sponsored
Sponsored
The main idea is to utilize a hash map (or dictionary) to count the occurrences of each element in the input array. This helps us determine how many rows we will need based on the maximum frequency of any element.
Then, we iteratively fill the 2D array by distributing each unique element to different rows, ensuring each row contains distinct integers.
Time Complexity: O(n), where n is the length of the array.
Space Complexity: O(n), because of the storage needed for the count map and result array.
1import java.util.*;
2
3public class Solution {
4 public static List<List<Integer>> convertArray(int[] nums) {
5 Map<Integer, Integer> count = new HashMap<>();
6 for (int num : nums) {
7 count.put(num, count.getOrDefault(num, 0) + 1);
8 }
9 int max_frequency = Collections.max(count.values());
10 List<List<Integer>> result = new ArrayList<>();
11 for (int i = 0; i < max_frequency; i++) {
12 result.add(new ArrayList<>());
13 }
14 int index = 0;
15 for (Map.Entry<Integer, Integer> entry : count.entrySet()) {
16 for (int i = 0; i < entry.getValue(); i++) {
17 result.get(index).add(entry.getKey());
18 index = (index + 1) % max_frequency;
19 }
20 }
21 return result;
22 }
23
24 public static void main(String[] args) {
25 int[] nums = {1, 3, 4, 1, 2, 3, 1};
26 List<List<Integer>> result = convertArray(nums);
27 for (List<Integer> row : result) {
28 System.out.println(row);
29 }
30 }
31}
The Java solution uses a HashMap to count occurrences, finds the maximum frequency, creates several lists for rows, and fills these lists in a round-robin method to ensure all rows contain distinct elements.
This approach first sorts the array to easily group identical elements. Starting from the least element, it places each new occurrence in different rows to ensure minimal rows while adhering to the distinct integer rule per row.
Time Complexity: O(n log n), because of sorting.
Space Complexity: O(n), for storing the result array.
1
This JavaScript solution sorts the input array and uses a loop to place numbers into non-repeating rows, starting a new row whenever necessary to maintain unique entries within each row.