I was trying to solve the LeetCode Question:: 1207: Unique Number of Occurrences.
My Way of Thinking:
- I will make a structures Occurences which will contain two sub-elements, count,element. Element will store the element while count will store the count of element.
- Now I will create a IN function which will check whether whether a element is present in Array of type Occurence.
- For count_occurences function, I will check whether Var is present in Array or not. If No, Then I add the element and it's count value to it. If Yes, then we increase the count value.
Code:
#include<iostream>
using namespace std;
typedef struct Occurence{
int element;
int count = 0;
}Occurence;
bool IN(Occurence Arr[],int var,int size){
for(int i=0;i<size;i++){
if(var == Arr[i].element){
return true;
}
else{
return false;
}
}
return false;
}
void count_Occurence(Occurence Array[],int Arr[],int size){
for(int i=0;i<size;i++){
int Var = Arr[i];
if( IN(Array,Var,size) ){
Array[i].count++;
}else{
Array[i].element = Var;
Array[i].count++;
}
}
}
int main(){
int Arr[1000];
int N;
cin >> N;
for(int i=0;i<N;i++){
cin >> Arr[i];
}
Occurence *Array = (Occurence*)malloc(N*sizeof(Occurence));
count_Occurence(Array,Arr,N);
int ans = 0;
for(int i=0;i<N;i++){
ans = ans ^ Array[i].count;
}
cout << ans;
return 0;
}
Problem:
- I initialized the value of count in structure definition as 0 but it isn't getting initialized as zero when I ran it. It's some garbage value. I am not able to understand why?