| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.RelativeSortArray; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class RelativeSortArrayCountingSort : IRelativeSortArray |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n + m + k), where k is the maximum element in arr1 |
| | 19 | | /// Space complexity - O(k), where k is the maximum element in arr1 |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="arr1"></param> |
| | 22 | | /// <param name="arr2"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public int[] RelativeSortArray(int[] arr1, int[] arr2) |
| 2 | 25 | | { |
| 2 | 26 | | var frequency = new int[1001]; |
| | 27 | |
|
| 40 | 28 | | foreach (var arr1Item in arr1) |
| 17 | 29 | | { |
| 17 | 30 | | frequency[arr1Item]++; |
| 17 | 31 | | } |
| | 32 | |
|
| 2 | 33 | | var index = 0; |
| | 34 | |
|
| 26 | 35 | | foreach (var num in arr2) |
| 10 | 36 | | { |
| 23 | 37 | | while (frequency[num] > 0) |
| 13 | 38 | | { |
| 13 | 39 | | arr1[index++] = num; |
| | 40 | |
|
| 13 | 41 | | frequency[num]--; |
| 13 | 42 | | } |
| 10 | 43 | | } |
| | 44 | |
|
| 4008 | 45 | | for (var i = 0; i < frequency.Length; i++) |
| 2002 | 46 | | { |
| 2006 | 47 | | while (frequency[i] > 0) |
| 4 | 48 | | { |
| 4 | 49 | | arr1[index++] = i; |
| | 50 | |
|
| 4 | 51 | | frequency[i]--; |
| 4 | 52 | | } |
| 2002 | 53 | | } |
| | 54 | |
|
| 2 | 55 | | return arr1; |
| 2 | 56 | | } |
| | 57 | | } |