|
| 1 | +## 06. Integer Break |
| 2 | + |
| 3 | + |
| 4 | +The problem can be found at the following link: [Question Link](https://leetcode.com/problems/majority-element-ii/description/) |
| 5 | + |
| 6 | + |
| 7 | +### My Approach |
| 8 | + |
| 9 | + |
| 10 | +1. Initialize variables: |
| 11 | + - `n` to store the size of the input vector `nums`. |
| 12 | + - Create an unordered map `cnt` to store the count of occurrences of each element. |
| 13 | + - Initialize an empty vector `ans` to store the majority elements. |
| 14 | + |
| 15 | +2. Iterate through the `nums` vector using a for loop: |
| 16 | + - Use the `cnt` map to count the occurrences of each element in the `nums` vector. |
| 17 | + |
| 18 | +3. Iterate through the elements in the `cnt` map: |
| 19 | + - Check if the count (`j->second`) of an element is greater than one-third of the total elements (`n/3`). |
| 20 | + - If the count meets the condition, add the element (`j->first`) to the `ans` vector. |
| 21 | + |
| 22 | +4. After both loops have finished, the `ans` vector will contain the majority elements (elements that appear more than one-third of the time) in the input vector `nums`. |
| 23 | + |
| 24 | +5. Return the `ans` vector as the result. |
| 25 | + |
| 26 | + |
| 27 | + |
| 28 | +### Time and Auxiliary Space Complexity |
| 29 | + |
| 30 | +- **Time Complexity**: `O(n)` |
| 31 | +- **Auxiliary Space Complexity**: `O(n)` |
| 32 | + |
| 33 | + |
| 34 | + |
| 35 | +### Code (C++) |
| 36 | + |
| 37 | +```cpp |
| 38 | + |
| 39 | +class Solution { |
| 40 | +public: |
| 41 | + vector<int> majorityElement(vector<int>& nums) { |
| 42 | + int n=nums.size(); |
| 43 | + unordered_map<int, int> cnt; |
| 44 | + vector<int> ans; |
| 45 | + for(int i=0;i<n;i++){ |
| 46 | + cnt[nums[i]]++; |
| 47 | + } |
| 48 | + for(auto j=cnt.begin();j!=cnt.end();j++){ |
| 49 | + if(j->second>n/3)ans.push_back(j->first); |
| 50 | + } |
| 51 | + return ans; |
| 52 | + } |
| 53 | +}; |
| 54 | + |
| 55 | +``` |
| 56 | +
|
| 57 | +### Contribution and Support |
| 58 | +
|
| 59 | +For discussions, questions, or doubts related to this solution, please visit our [discussion section](https://leetcode.com/discuss/general-discussion). We welcome your input and aim to foster a collaborative learning environment. |
| 60 | +
|
| 61 | +If you find this solution helpful, consider supporting us by giving a `⭐ star` to the [rishabhv12/Daily-Leetcode-Solution](https://github.com/rishabhv12/Daily-Leetcode-Solution) repository. |
0 commit comments