[LeetCode] Number of Unique Categories

2782. Number of Unique Categories

You are given an integer n and an object categoryHandler of class CategoryHandler.

There are nelements, numbered from 0 to n - 1. Each element has a category, and your task is to find the number of unique categories.

The class CategoryHandler contains the following function, which may help you:

  • boolean haveSameCategory(integer a, integer b): Returns true if a and b are in the same category and false otherwise. Also, if either a or b is not a valid number (i.e. it’s greater than or equal to nor less than 0), it returns false.

Return the number of unique categories.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Definition for a category handler.
* class CategoryHandler {
* public:
* CategoryHandler(vector<int> categories);
* bool haveSameCategory(int a, int b);
* };
*/
class Solution {
public:
int numberOfCategories(int n, CategoryHandler* categoryHandler) {
vector<bool> ok(n,true);
int res = 0;
for(int i = 0; i < n; i++) {
if(!ok[i]) continue;
res += 1;
for(int j = i+1; j < n; j++) {
if(!ok[j]) continue;
ok[j] = !categoryHandler->haveSameCategory(i,j);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/08/11/PS/LeetCode/number-of-unique-categories/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.