Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique.
Example:
Input: arr[]={1,2,2,1,1,3} Output: true
Approach
Java
import java.util.HashMap;import java.util.HashSet;import java.util.Set;public class UniqueNumberofOccurrences {public static void main(String[] args) {int arr[] = { 1, 2, 2, 1, 1, 3 };System.out.println(uniqueOccurrences(arr));}// method to check unique Occurrencesprivate static boolean uniqueOccurrences(int[] arr) {// map for frequency count of each elementHashMap<Integer, Integer> map = new HashMap<>();for (int i = 0; i < arr.length; i++) {map.put(arr[i], map.getOrDefault(arr[i], 0) + 1);}Set<Integer> set = new HashSet<>();// iterate till end of mapfor (Integer key : map.keySet()) {// of not unique then return false;if (set.contains(map.get(key))) {return false;}set.add(map.get(key));}return true;}}
C++
#include <bits/stdc++.h>using namespace std;//function to check for unique occurrencesbool uniqueOccurrences(vector<int>& arr){map<int,int> mp;for(int i=0;i<arr.size();i++)mp[arr[i]]++;bool flag=true;set<int> st;for(int i=0;i<arr.size();i++){if(mp[arr[i]]>0&&st.find(mp[arr[i]])!=st.end()){flag=false;break;}st.insert(mp[arr[i]]);mp[arr[i]]=0;}return flag;}int main(){vector<int> arr ={1,2,2,1,1,3};if(uniqueOccurrences(arr))cout<<"true\n";elsecout<<"false\n";return 0;}
No comments:
Post a Comment