Mode of Elements in Sorted Vector in C++
Last Updated :
05 Feb, 2024
A number that occurs most frequently and has the highest frequency is considered a mode of the dataset. In this article, we will learn how to find the mode of all elements in a sorted vector of ints in C++.
Example
Input: myVector= {1,2,3,3,5,5,5,5,6,7}
Output: Mode is 5
Find the Mode of Vector Elements
To find a mode of all elements in a sorted vector, we can use the idea that the given vector is already sorted which means that the elements already occur in ascending order so we only need to see the maximum count until now and update it if it increases.
C++ Program to Find Mode in Vector of Integers in C++
The below program demonstrates how we can find a mode among elements in a sorted vector of ints in C++.
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > a = { 1, 2, 2, 3, 4, 4, 4, 5, 5, 5, 5 };
int n = a.size();
int mode = a[0];
int curr_count = 1;
int max_count = 1;
for ( int i = 1; i < n; ++i) {
if (a[i] == a[i - 1]) {
++curr_count;
}
else {
if (curr_count > max_count) {
max_count = curr_count;
mode = a[i - 1];
}
curr_count = 1;
}
}
if (curr_count > max_count) {
mode = a[n - 1];
}
if (mode != -1) {
cout << "Mode is: " << mode << endl;
}
else {
cout << "No mode found." << endl;
}
return 0;
}
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...