"n/3 number appears in array elements" Code Answer's
You're definitely familiar with the best coding language Whatever that developers use to develop their projects and they get all their queries like "n/3 number appears in array elements" answered properly. Developers are finding an appropriate answer about n/3 number appears in array elements related to the Whatever coding language. By visiting this online portal developers get answers concerning Whatever codes question like n/3 number appears in array elements. Enter your desired code related query in the search bar and get every piece of information about Whatever code related question on n/3 number appears in array elements.
n/3 number appears in array elements
// CPP program to find if any element appears
// more than n/3.
#include <bits/stdc++.h>
using namespace std;
int appearsNBy3(int arr[], int n)
{
int count1 = 0, count2 = 0;
int first=INT_MAX , second=INT_MAX ;
for (int i = 0; i < n; i++) {
// if this element is previously seen,
// increment count1.
if (first == arr[i])
count1++;
// if this element is previously seen,
// increment count2.
else if (second == arr[i])
count2++;
else if (count1 == 0) {
count1++;
first = arr[i];
}
else if (count2 == 0) {
count2++;
second = arr[i];
}
// if current element is different from
// both the previously seen variables,
// decrement both the counts.
else {
count1--;
count2--;
}
}
count1 = 0;
count2 = 0;
// Again traverse the array and find the
// actual counts.
for (int i = 0; i < n; i++) {
if (arr[i] == first)
count1++;
else if (arr[i] == second)
count2++;
}
if (count1 > n / 3)
return first;
if (count2 > n / 3)
return second;
return -1;
}
int main()
{
int arr[] = { 1, 2, 3, 1, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << appearsNBy3(arr, n) << endl;
return 0;
}
All those coders who are working on the Whatever based application and are stuck on n/3 number appears in array elements can get a collection of related answers to their query. Programmers need to enter their query on n/3 number appears in array elements related to Whatever code and they'll get their ambiguities clear immediately. On our webpage, there are tutorials about n/3 number appears in array elements for the programmers working on Whatever code while coding their module. Coders are also allowed to rectify already present answers of n/3 number appears in array elements while working on the Whatever language code. Developers can add up suggestions if they deem fit any other answer relating to "n/3 number appears in array elements". Visit this developer's friendly online web community, CodeProZone, and get your queries like n/3 number appears in array elements resolved professionally and stay updated to the latest Whatever updates.