Пожалуйста, прочтите новое правило об ограничении использования AI-инструментов. ×

Блог пользователя d0uch3b4g

Автор d0uch3b4g, история, 7 лет назад, По-английски

Is there any efficient way to count occurrences of elements while taking input in an array (without using STL, Nested Loop)?? If so, then what's that process and what will be the complexity??

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

»
7 лет назад, # |
  Проголосовать: нравится +1 Проголосовать: не нравится

If elements of array have  ≤ 107 upper bound, so you can use array to count them. If they can be big numbers, I don't think there is better way than map (or unordered_map). Complexity will be O(1) while using array, O(logN) otherwise.

int cnt[10000000]; // declare this as global to prevent memory overflow.
for (int i = 1; i <= n; i++) {
    cin >> arr[i]; cnt[arr[i]]++;
}