
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Majority Element II in C++
Suppose we have one integer array; we have to find those elements that appear more than floor of n/3. Here n is the size of array.
So if the input is like [1,1,1,3,3,2,2,2], then the results will be [1,2]
To solve this, we will follow these steps −
first := 0, second := 1, cnt1 := 0, cnt2 := 0, n := size of array nums
-
for i in range 0 to size of n – 1
x := nums[i]
if x is first, then increase cnt by 1,
otherwise when x is second, then increase cnt2 by 1
otherwise when cnt1 is 0, then set first as x and cnt1 := 1
otherwise when cnt2 is 0, then set second as x and cnt2 := 1
otherwise decrease cnt1 and cnt2 by 1
set cnt1 := 0 and cnt2 := 0
-
for i in range 0 to n – 1
if nums[i] = first, then increase cnt1 by 1, otherwise when nums[i] is second, then increase cnt2 by 1
make an array called ret
if cnt1 > n / 3, then insert first into ret
if cnt2 > n / 3, then insert second into ret
return ret.
Example(C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; void print_vector(vector<auto> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: vector<int> majorityElement(vector<int>& nums) { int first = 0; int second = 1; int cnt1 = 0; int cnt2 = 0; int n = nums.size(); for(int i = 0; i < n; i++){ int x = nums[i]; if(x == first){ cnt1++; } else if(x == second){ cnt2++; } else if(cnt1 == 0){ first = x; cnt1 = 1; } else if(cnt2 == 0){ second = x; cnt2 = 1; } else { cnt1--; cnt2--; } } cnt1 = 0; cnt2 = 0; for(int i = 0; i < n; i++){ if(nums[i] == first)cnt1++; else if(nums[i] == second)cnt2++; } vector <int> ret; if(cnt1 > n / 3)ret.push_back(first); if(cnt2 > n / 3)ret.push_back(second); return ret; } }; main(){ Solution ob; vector<int> v = {1, 1, 1, 3, 3, 2, 2, 2}; print_vector(ob.majorityElement(v)); }
Input
[1,1,1,3,3,2,2,2]
Output
[2, 1, ]