Skip to content

Commit 446d2fa

Browse files
committed
Merge branch 'main' of github.com:hogan-tech/leetcode-solution
2 parents 16b1d81 + fe1f0a5 commit 446d2fa

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# time complexity: O(n)
2+
# space complexity: O(n)
3+
from typing import List
4+
5+
class Solution:
6+
def findMatrix(self, nums: List[int]) -> List[List[int]]:
7+
frequency = [0] * (len(nums) + 1)
8+
res = [[]]
9+
for i in nums:
10+
if frequency[i] >= len(res):
11+
res.append([])
12+
res[frequency[i]].append(i)
13+
frequency[i] += 1
14+
return res
15+
16+
nums = [1, 3, 4, 1, 2, 3, 1]
17+
print(Solution().findMatrix(nums))
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<h2><a href="https://leetcode.com/problems/convert-an-array-into-a-2d-array-with-conditions/">2610. Convert an Array Into a 2D Array With Conditions</a></h2><h3>Medium</h3><hr><div><p>You are given an integer array <code>nums</code>. You need to create a 2D array from <code>nums</code> satisfying the following conditions:</p>
2+
3+
<ul>
4+
<li>The 2D array should contain <strong>only</strong> the elements of the array <code>nums</code>.</li>
5+
<li>Each row in the 2D array contains <strong>distinct</strong> integers.</li>
6+
<li>The number of rows in the 2D array should be <strong>minimal</strong>.</li>
7+
</ul>
8+
9+
<p>Return <em>the resulting array</em>. If there are multiple answers, return any of them.</p>
10+
11+
<p><strong>Note</strong> that the 2D array can have a different number of elements on each row.</p>
12+
13+
<p>&nbsp;</p>
14+
<p><strong class="example">Example 1:</strong></p>
15+
16+
<pre><strong>Input:</strong> nums = [1,3,4,1,2,3,1]
17+
<strong>Output:</strong> [[1,3,4,2],[1,3],[1]]
18+
<strong>Explanation:</strong> We can create a 2D array that contains the following rows:
19+
- 1,3,4,2
20+
- 1,3
21+
- 1
22+
All elements of nums were used, and each row of the 2D array contains distinct integers, so it is a valid answer.
23+
It can be shown that we cannot have less than 3 rows in a valid array.</pre>
24+
25+
<p><strong class="example">Example 2:</strong></p>
26+
27+
<pre><strong>Input:</strong> nums = [1,2,3,4]
28+
<strong>Output:</strong> [[4,3,2,1]]
29+
<strong>Explanation:</strong> All elements of the array are distinct, so we can keep all of them in the first row of the 2D array.
30+
</pre>
31+
32+
<p>&nbsp;</p>
33+
<p><strong>Constraints:</strong></p>
34+
35+
<ul>
36+
<li><code>1 &lt;= nums.length &lt;= 200</code></li>
37+
<li><code>1 &lt;= nums[i] &lt;= nums.length</code></li>
38+
</ul>
39+
</div>

0 commit comments

Comments
 (0)