This approach involves using a HashMap (or dictionary in Python) to count the occurrences of each element in the array. This will help in efficiently checking if an element exists and how many times it appears, which is useful for problems requiring frequency analysis.
Time Complexity: O(n), as it iterates over the array once. Space Complexity: O(1) if the element range is known and constant, or O(k) where k is the range of elements.
1using System;
2using System.Collections.Generic;
3
4class ElementCounter {
5 static void CountElements(int[] arr) {
6 Dictionary<int, int> frequency = new Dictionary<int, int>();
7 foreach (int num in arr) {
8 if (frequency.ContainsKey(num)) {
9 frequency[num]++;
10 } else {
11 frequency[num] = 1;
12 }
13 }
14 foreach (var kvp in frequency) {
15 Console.WriteLine($"Element {kvp.Key} appears {kvp.Value} times");
16 }
17 }
18
19 static void Main() {
20 int[] arr = {1, 3, 1, 2, 3, 4, 5, 3};
21 CountElements(arr);
22 }
23}
The C# solution uses the Dictionary class to count frequencies of elements. This approach benefits from C#'s efficient implementation of hash tables for rapid insertion and lookup.
Another approach is sorting the array and then identifying repeated elements by comparison with neighboring elements. This leverages the efficiency of modern sorting algorithms to bring repeated elements together, making it trivial to count consecutive duplicates.
Time Complexity: O(n log n) due to the sort operation. Space Complexity: O(1) if in-place sorting is considered.
1import java.util.Arrays;
2
3public class ElementSorter {
4 public static void countSortedElements(int[] arr) {
5 Arrays.sort(arr);
6 int count = 1;
7 for (int i = 1; i < arr.length; i++) {
8 if (arr[i] == arr[i - 1]) {
9 count++;
10 } else {
11 System.out.println("Element " + arr[i - 1] + " appears " + count + " times");
12 count = 1;
13 }
14 }
15 System.out.println("Element " + arr[arr.length - 1] + " appears " + count + " times");
16 }
17
18 public static void main(String[] args) {
19 int[] arr = {1, 3, 1, 2, 3, 4, 5, 3};
20 countSortedElements(arr);
21 }
22}
The Java solution utilizes the built-in Arrays.sort to organize elements, after which a single loop suffices for counting and printing frequency of each distinct element.