C++ 中的众数元素 II

c++server side programmingprogramming

假设我们有一个整数数组;我们需要找出出现次数超过 n/3 的元素。这里 n 是数组的大小。

因此,如果输入为 [1,1,1,3,3,2,2,2],则结果为 [1,2]

为了解决这个问题,我们将遵循以下步骤 −

  • first := 0, second := 1, cnt1 := 0, cnt2 := 0, n := 数组 nums 的大小

  • for i in range 0 to n – 1

    • x := nums[i]

    • 如果 x 为第一个,则将 cnt 加 1

    • 否则,当 x 为第二个时,则将 cnt2 加 1

    • 否则,当 cnt1 为 0 时,将第一个设置为 x,且 cnt1 := 1

    • 否则,当 cnt2 为 0 时,将第二个设置为 x,且 cnt2 := 1

    • 否则,将 cnt1 和 cnt2 减 1

  • 设置 cnt1 := 0,cnt2 := 0

  • 对于 i 在 0 到 n 范围内的情况 – 1

    • 如果 nums[i] = first,则将 cnt1 加 1;否则,当 nums[i] 为 second 时,将 cnt2 加 1

  • 创建一个名为 ret 的数组

  • 如果 cnt1 > n / 3,则将 first 插入 ret 中

  • 如果 cnt2 > n / 3,则将 second 插入 ret 中

  • 返回 ret。

示例(C++)

让我们看下面的实现,以便更好地理解 −

#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));
}

输入

[1,1,1,3,3,2,2,2]

输出

[2, 1, ]

相关文章