根据元素在 0 到 n-1 范围内的频率填充数组
给定一个允许重复的正整数数组。该数组包含范围从 0 到 n-1 的元素。任务是填充数组,使 arr[i] 包含 i 的频率。
例子 :
Input : arr[] = {1, 4, 3, 4, 1, 1, 4, 4, 4, 7}
Output : arr[] = {0, 3, 0, 1, 5, 0, 0, 1, 0, 0}
Here 0 appears 0 times, so arr[0] is 0
1 appears 3 times
2 appears 0 times
3 appears 0 times
4 appears 5 times
..........
Input : arr[] = {1, 2, 3, 4, 1, 1, 4, 5, 6, 7}
Output : arr[] = {0, 3, 1, 1, 2, 1, 1, 1, 0, 0}
这个问题的一个简单解决方案是运行两个循环。外循环一一挑选元素。内部循环计算拾取元素的频率并将频率存储在最终数组中。
一个有效的解决方案是使用大小为 n 的辅助数组。
1) Create an array temp[0..n-1] and
initialize it as 0.
2) Traverse given array and do following
for every element arr[i].
temp[arr[i]]++
3) Copy temp[] to arr[].
下面是上述步骤的实现。
C++
// C++ program to fill an array with frequencies.
#include
using namespace std;
// Fills arr[] with frequencies of elements
void fillWithFreq(int arr[], int n)
{
int temp[n];
memset(temp, 0, sizeof(temp));
// Fill temp with frequencies
for (int i=0; i
Java
// Java program to fill an array with frequencies.
import java.util.Arrays;
class GFG {
// Fills arr[] with frequencies of elements
static void fillWithFreq(int arr[], int n)
{
int temp[]=new int[n];
Arrays.fill(temp, 0);
// Fill temp with frequencies
for (int i = 0; i < n; i++)
temp[arr[i]] += 1;
// Copy temp to array
for (int i = 0; i < n; i++)
arr[i] = temp[i];
}
// Driver method
public static void main(String[] args)
{
int arr[] = {5, 2, 3, 4, 5, 5, 4, 5, 6, 7};
int n = arr.length;
fillWithFreq(arr, n);
for (int i=0; i
Python3
# Python3 program to fill an
# array with frequencies.
# Fills arr[] with frequencies of elements
def fillWithFreq(arr, n):
temp = [0 for i in range(n)]
# Fill temp with frequencies
for i in range(n):
temp[arr[i]] += 1
# Copy temp to array
for i in range(n):
arr[i] = temp[i]
# Driver Code
arr = [5, 2, 3, 4, 5, 5, 4, 5, 6, 7]
n = len(arr)
fillWithFreq(arr, n)
for i in range(n):
print(arr[i], end = " ")
# This code is contributed by Anant Agarwal.
C#
// C# program to fill an
// array with frequencies.
using System;
class GFG {
// Fills arr[] with frequencies of elements
static void fillWithFreq(int []arr, int n)
{
int []temp = new int[n];
for(int i = 0; i < n; i++)
temp[i] = 0;
// Fill temp with frequencies
for (int i = 0; i < n; i++)
temp[arr[i]] += 1;
// Copy temp to array
for (int i = 0; i < n; i++)
arr[i] = temp[i];
}
// Driver method
public static void Main()
{
int []arr = {5, 2, 3, 4, 5,
5, 4, 5, 6, 7};
int n = arr.Length;
// Function calling
fillWithFreq(arr, n);
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
}
// This code is contributed by nitin mittal.
PHP
Javascript
输出 :
0 0 1 1 2 4 1 1 0 0
时间复杂度: O(n)
辅助空间: O(n)