Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // follow on github: https://github.com/ivandrofly
- namespace FindDuplicatesElement
- {
- using System;
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("Hello World!");
- int[] list = { 1, 3, 1, 23, 4, 2, 2, 3, 3, 2, 3, 3, 32, 2, 2, 23, 45, 5, 5, 1, 2, 3, 4, 16, 61, 3, 4 };
- FindDuplicates(list);
- Console.ReadLine();
- }
- private static void FindDuplicates(int[] a)
- {
- // [1, 2, 2, 3, 4,5,5,5]
- // # solution 1
- // find max element in array
- // create an array with the size of max
- // for each number increment the index that number presend when a match is found
- int max = GetMax(a);
- // note: the +1 is that the array starts from 0 so it fix the out-of bound problem
- int[] countArray = new int[max + 1];
- for (int i = 0; i < a.Length; i++)
- {
- int item = a[i];
- countArray[item]++;
- }
- for (int i = 0; i < countArray.Length; i++)
- {
- if (countArray[i] > 0)
- {
- Console.WriteLine($"Value: {i} repeater: {countArray[i]}");
- }
- }
- // # solution 2
- // TODO: create a dictionary where key is the number found in list and increment the value accordingly when the key match in dictionary
- }
- private static int GetMax(int[] array)
- {
- int max = array[0];
- for (int i = 1; i < array.Length; i++)
- {
- if (array[i] > max)
- {
- max = array[i];
- }
- }
- return max;
- }
- }
- }
Add Comment
Please, Sign In to add comment