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.
1using System.Collections.Generic;
public class Solution {
public static List<List<int>> ConvertArray(int[] nums) {
Array.Sort(nums);
List<List<int>> result = new List<List<int>>();
foreach (var num in nums) {
bool placed = false;
foreach (var row in result) {
if (!row.Contains(num)) {
row.Add(num);
placed = true;
break;
}
}
if (!placed) {
List<int> newRow = new List<int>();
newRow.Add(num);
result.Add(newRow);
}
}
return result;
}
public static void Main() {
int[] nums = {1, 3, 4, 1, 2, 3, 1};
var result = ConvertArray(nums);
foreach (var row in result) {
Console.WriteLine(string.Join(" ", row));
}
}
}
The C# implementation sorts the array, tries to place each integer in existing non-repetitive rows, creating new ones when required, thus ensuring minimum necessary rows.