给定一个带有重复的未排序数组,任务是对多个出现的单个元素进行分组。分组应该以保持所有元素首次出现的顺序的方式进行。
例子:
Input: arr[] = {5, 3, 5, 1, 3, 3}
Output: {5, 5, 3, 3, 3, 1}
Input: arr[] = {4, 6, 9, 2, 3, 4, 9, 6, 10, 4}
Output: {4, 4, 4, 6, 6, 9, 9, 2, 3, 10}
简单的解决方案是使用嵌套循环。外循环逐个遍历数组元素。内循环检查这是否是第一次出现,如果是,则内循环打印它和所有其他出现。
C++
// A simple C++ program to group multiple occurrences of individual
// array elements
#include
using namespace std;
// A simple method to group all occurrences of individual elements
void groupElements(int arr[], int n)
{
// Initialize all elements as not visited
bool *visited = new bool[n];
for (int i=0; i
Java
// A simple Java program to group
// multiple occurrences of individual
// array elements
class GFG
{
// A simple method to group all occurrences
// of individual elements
static void groupElements(int arr[], int n)
{
// Initialize all elements as not visited
boolean visited[] = new boolean[n];
for (int i = 0; i < n; i++)
{
visited[i] = false;
}
// Traverse all elements
for (int i = 0; i < n; i++)
{
// Check if this is first occurrence
if (!visited[i])
{
// If yes, print it and all
// subsequent occurrences
System.out.print(arr[i] + " ");
for (int j = i + 1; j < n; j++)
{
if (arr[i] == arr[j])
{
System.out.print(arr[i] + " ");
visited[j] = true;
}
}
}
}
}
/* Driver code */
public static void main(String[] args)
{
int arr[] = {4, 6, 9, 2, 3, 4,
9, 6, 10, 4};
int n = arr.length;
groupElements(arr, n);
}
}
// This code is contributed by Rajput-JI
Python3
# A simple Python 3 program to
# group multiple occurrences of
# individual array elements
# A simple method to group all
# occurrences of individual elements
def groupElements(arr, n):
# Initialize all elements
# as not visited
visited = [False] * n
for i in range(0, n):
visited[i] = False
# Traverse all elements
for i in range(0, n):
# Check if this is
# first occurrence
if (visited[i] == False):
# If yes, print it and
# all subsequent occurrences
print(arr[i], end = " ")
for j in range(i + 1, n):
if (arr[i] == arr[j]):
print(arr[i], end = " ")
visited[j] = True
# Driver Code
arr = [4, 6, 9, 2, 3,
4, 9, 6, 10, 4]
n = len(arr)
groupElements(arr, n)
# This code is contributed
# by Smitha
C#
// A simple C# program to group
// multiple occurrences of individual
// array elements
using System;
class GFG
{
// A simple method to group all occurrences
// of individual elements
static void groupElements(int []arr, int n)
{
// Initialize all elements as not visited
bool []visited = new bool[n];
for (int i = 0; i < n; i++)
{
visited[i] = false;
}
// Traverse all elements
for (int i = 0; i < n; i++)
{
// Check if this is first occurrence
if (!visited[i])
{
// If yes, print it and all
// subsequent occurrences
Console.Write(arr[i] + " ");
for (int j = i + 1; j < n; j++)
{
if (arr[i] == arr[j])
{
Console.Write(arr[i] + " ");
visited[j] = true;
}
}
}
}
}
/* Driver code */
public static void Main(String[] args)
{
int []arr = {4, 6, 9, 2, 3, 4,
9, 6, 10, 4};
int n = arr.Length;
groupElements(arr, n);
}
}
// This code is contributed by PrinciRaj1992
Javascript
Java
/* Java program to group multiple occurrences of individual array elements */
import java.util.HashMap;
class Main
{
// A hashing based method to group all occurrences of individual elements
static void orderedGroup(int arr[])
{
// Creates an empty hashmap
HashMap hM = new HashMap();
// Traverse the array elements, and store count for every element
// in HashMap
for (int i=0; i
Python3
# Python3 program to group multiple
# occurrences of individual array elements
# A hashing based method to group
# all occurrences of individual elements
def orderedGroup(arr):
# Creates an empty hashmap
hM = {}
# Traverse the array elements, and store
# count for every element in HashMap
for i in range(0, len(arr)):
# Increment count of elements
# in HashMap
hM[arr[i]] = hM.get(arr[i], 0) + 1
# Traverse array again
for i in range(0, len(arr)):
# Check if this is first occurrence
count = hM.get(arr[i], None)
if count != None:
# If yes, then print
# the element 'count' times
for j in range(0, count):
print(arr[i], end = " ")
# And remove the element from HashMap.
del hM[arr[i]]
# Driver Code
if __name__ == "__main__":
arr = [10, 5, 3, 10, 10, 4, 1, 3]
orderedGroup(arr)
# This code is contributed by Rituraj Jain
C#
// C# program to group multiple occurrences
// of individual array elements
using System;
using System.Collections.Generic;
class GFG
{
// A hashing based method to group
// all occurrences of individual elements
static void orderedGroup(int []arr)
{
// Creates an empty hashmap
Dictionary hM = new Dictionary();
// Traverse the array elements,
// and store count for every element in HashMap
for (int i = 0; i < arr.Length; i++)
{
// Check if element is already in HashMap
int prevCount = 0;
if (hM.ContainsKey(arr[i]))
prevCount = hM[arr[i]];
// Increment count of element element in HashMap
if (hM.ContainsKey(arr[i]))
hM[arr[i]] = prevCount + 1;
else
hM.Add(arr[i], prevCount + 1);
}
// Traverse array again
for (int i = 0; i < arr.Length; i++)
{
// Check if this is first occurrence
int count = 0;
if (hM.ContainsKey(arr[i]))
count = hM[arr[i]];
if (count != 0)
{
// If yes, then print the
// element 'count' times
for (int j = 0; j < count; j++)
Console.Write(arr[i] + " ");
// And remove the element from HashMap.
hM.Remove(arr[i]);
}
}
}
// Driver Code
public static void Main (String[] args)
{
int []arr = {10, 5, 3, 10, 10, 4, 1, 3};
orderedGroup(arr);
}
}
// This code is contributed by Princi Singh
Javascript
输出:
4 4 4 6 6 9 9 2 3 10
上述方法的时间复杂度为 O(n 2 )。
基于二叉搜索树的方法:使用自平衡二叉搜索树(如红黑树或 AVL 树)可以将时间复杂度提高到 O(nLogn)。以下是完整的算法。
1)创建一个空的二叉搜索树(BST)。每个 BST 节点都将包含一个数组元素及其计数。
2)遍历输入数组并对每个元素执行以下操作。
……..a) 如果元素在 BST 中不存在,则将其插入,计数为 0。
……..b) 如果元素存在,则在相应的 BST 节点中增加计数。
3)再次遍历数组并对每个元素执行以下操作。
…….. 如果元素存在于 BST 中,则执行以下操作
……….a) 获取其计数并打印元素“计数”次。
……….b) 从 BST 中删除元素。
上述解决方案的时间复杂度为 O(nLogn)。
基于散列的方法:我们也可以使用散列。这个想法是在上述算法中用哈希映射替换二叉搜索树。
下面是基于散列的解决方案的实现。
Java
/* Java program to group multiple occurrences of individual array elements */
import java.util.HashMap;
class Main
{
// A hashing based method to group all occurrences of individual elements
static void orderedGroup(int arr[])
{
// Creates an empty hashmap
HashMap hM = new HashMap();
// Traverse the array elements, and store count for every element
// in HashMap
for (int i=0; i
蟒蛇3
# Python3 program to group multiple
# occurrences of individual array elements
# A hashing based method to group
# all occurrences of individual elements
def orderedGroup(arr):
# Creates an empty hashmap
hM = {}
# Traverse the array elements, and store
# count for every element in HashMap
for i in range(0, len(arr)):
# Increment count of elements
# in HashMap
hM[arr[i]] = hM.get(arr[i], 0) + 1
# Traverse array again
for i in range(0, len(arr)):
# Check if this is first occurrence
count = hM.get(arr[i], None)
if count != None:
# If yes, then print
# the element 'count' times
for j in range(0, count):
print(arr[i], end = " ")
# And remove the element from HashMap.
del hM[arr[i]]
# Driver Code
if __name__ == "__main__":
arr = [10, 5, 3, 10, 10, 4, 1, 3]
orderedGroup(arr)
# This code is contributed by Rituraj Jain
C#
// C# program to group multiple occurrences
// of individual array elements
using System;
using System.Collections.Generic;
class GFG
{
// A hashing based method to group
// all occurrences of individual elements
static void orderedGroup(int []arr)
{
// Creates an empty hashmap
Dictionary hM = new Dictionary();
// Traverse the array elements,
// and store count for every element in HashMap
for (int i = 0; i < arr.Length; i++)
{
// Check if element is already in HashMap
int prevCount = 0;
if (hM.ContainsKey(arr[i]))
prevCount = hM[arr[i]];
// Increment count of element element in HashMap
if (hM.ContainsKey(arr[i]))
hM[arr[i]] = prevCount + 1;
else
hM.Add(arr[i], prevCount + 1);
}
// Traverse array again
for (int i = 0; i < arr.Length; i++)
{
// Check if this is first occurrence
int count = 0;
if (hM.ContainsKey(arr[i]))
count = hM[arr[i]];
if (count != 0)
{
// If yes, then print the
// element 'count' times
for (int j = 0; j < count; j++)
Console.Write(arr[i] + " ");
// And remove the element from HashMap.
hM.Remove(arr[i]);
}
}
}
// Driver Code
public static void Main (String[] args)
{
int []arr = {10, 5, 3, 10, 10, 4, 1, 3};
orderedGroup(arr);
}
}
// This code is contributed by Princi Singh
Javascript
输出:
10 10 10 5 3 3 4 1
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。