最小化数组分区,使得一个元素在每个分区中最多重复一次
给定一个由正整数组成的数组arr[] 。如果arr[]中的每个元素最多可以是一个 group的一部分,并且一个数字只能重复一次,则任务是最小化形成的连续组。
例子:
Input: arr[] = {1, 2, 1, 1, 1, 1, 1, 2, 3}
Output: { {1, 2, 1}, {1, 1}, {1, 1, 2, 3} }
Explanation: Following are the groups formed with given conditions.
In 1 2 1, 1 repeats 1 times.
In 1 1, 1 repeats 1 times.
In 1 1 2 3, 1 repeats 1 times.
Therefore, in total there are three groups formed, which is minimum possible.
Input: arr[] = {1, 1}
Output: { {1, 1} }
方法:这个问题可以通过使用HashMaps来解决。请按照以下步骤解决给定的问题。
- 假设一个变量, count = 0用于存储形成的组数和一个2D向量用于存储组。
- 遍历数组arr[]并开始将数组元素的频率存储在map中,并将当前元素存储在vector中。
- 每当任何元素的频率变为2时,使用一个标志变量来跟踪一个频率为 2 的数字之前遇到过,然后继续前进。使用该标志变量来破坏任何组并增加计数变量并将向量推入2D向量并清除整个临时向量和map 。
- 现在打印二维向量作为所需的答案。
下面是上述方法的实现:
C++
// C++ program for above approach
#include
using namespace std;
// Function to find minimum groups
// formed with given conditions
void findMinimumGroups(int a[], int n)
{
map m;
// 2D vector to store groups
vector > v;
int c = 0;
vector v1;
bool to = 0;
for (int i = 0; i < n; i++) {
v1.push_back(a[i]);
// Store frequency
m[a[i]]++;
// Counting number of groups
if (m[a[i]] >= 2) {
if (to or m[a[i]] == 3) {
c++;
// If element found again
// push in 2d vector
m.clear();
v1.pop_back();
v.push_back(v1);
v1.clear();
to = 0;
i--;
}
else
to = 1;
}
else if (i == n - 1) {
c++;
v.push_back(v1);
}
}
for (int i = 0; i < v.size(); i++) {
for (int j = 0; j < v[i].size(); j++) {
cout << v[i][j] << " ";
}
cout << endl;
}
}
// Driver Code
int main()
{
int arr[] = { 1, 2, 1, 1, 1, 1, 1, 2, 3 };
int N = sizeof(arr) / sizeof(arr[0]);
// Function Call
findMinimumGroups(arr, N);
}
Python3
# Python code for the above approach
# Function to find minimum groups
# formed with given conditions
def findMinimumGroups(a, n):
m = dict()
# 2D vector to store groups
v = []
c = 0
v1 = []
to = 0
i = 0
while(i < n):
v1.append(a[i])
# Store frequency
if (a[i] in m):
m[a[i]] = m[a[i]]+1
else:
m[a[i]] = 1
# Counting number of groups
if (m[a[i]] >= 2):
if(to or m[a[i]] == 3):
c += 1
# If element found again
# append in 2d vector
m.clear()
v1.pop()
v.append(v1)
v1 = []
to = 0
i -= 1
else:
to = 1
elif (i == n - 1):
c += 1
v.append(v1)
i += 1
for i in range(len(v)):
for j in range(len(v[i])):
print(v[i][j], end = " ")
print()
# Driver Code
arr = [1, 2, 1, 1, 1, 1, 1, 2, 3]
N = len(arr)
# Function Call
findMinimumGroups(arr, N)
# This code is contributed by shinjanpatra
Javascript
输出
1 2 1
1 1
1 1 2 3
时间复杂度: O(N)
辅助空间: O(N)