You are given an integer n and an object categoryHandler of class CategoryHandler.
There are n elements, 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.
Example 1:
Input: n = 6, categoryHandler = [1,1,2,2,3,3]
Output: 3
Explanation: There are 6 elements in this example. The first two elements belong to category 1, the second two belong to category 2, and the last two elements belong to category 3. So there are 3 unique categories.
Example 2:
Input: n = 5, categoryHandler = [1,2,3,4,5]
Output: 5
Explanation: There are 5 elements in this example. Each element belongs to a unique category. So there are 5 unique categories.
Example 3:
Input: n = 3, categoryHandler = [1,1,1]
Output: 1
Explanation: There are 3 elements in this example. All of them belong to one category. So there is only 1 unique category.
Constraints:
1 <= n <= 100
Solutions
Solution 1
1 2 3 4 5 6 7 8 910111213141516171819
# Definition for a category handler.# class CategoryHandler:# def haveSameCategory(self, a: int, b: int) -> bool:# passclassSolution:defnumberOfCategories(self,n:int,categoryHandler:Optional['CategoryHandler'])->int:deffind(x:int)->int:ifp[x]!=x:p[x]=find(p[x])returnp[x]p=list(range(n))forainrange(n):forbinrange(a+1,n):ifcategoryHandler.haveSameCategory(a,b):p[find(a)]=find(b)returnsum(i==xfori,xinenumerate(p))
/** * Definition for a category handler. * class CategoryHandler { * public CategoryHandler(int[] categories); * public boolean haveSameCategory(int a, int b); * }; */classSolution{privateint[]p;publicintnumberOfCategories(intn,CategoryHandlercategoryHandler){p=newint[n];for(inti=0;i<n;++i){p[i]=i;}for(inta=0;a<n;++a){for(intb=a+1;b<n;++b){if(categoryHandler.haveSameCategory(a,b)){p[find(a)]=find(b);}}}intans=0;for(inti=0;i<n;++i){if(i==p[i]){++ans;}}returnans;}privateintfind(intx){if(p[x]!=x){p[x]=find(p[x]);}returnp[x];}}
/** * Definition for a category handler. * class CategoryHandler { * public: * CategoryHandler(vector<int> categories); * bool haveSameCategory(int a, int b); * }; */classSolution{public:intnumberOfCategories(intn,CategoryHandler*categoryHandler){vector<int>p(n);iota(p.begin(),p.end(),0);function<int(int)>find=[&](intx){if(p[x]!=x){p[x]=find(p[x]);}returnp[x];};for(inta=0;a<n;++a){for(intb=a+1;b<n;++b){if(categoryHandler->haveSameCategory(a,b)){p[find(a)]=find(b);}}}intans=0;for(inti=0;i<n;++i){ans+=i==p[i];}returnans;}};