标签:for 大于 ++ cto else ack solution nbsp push
1 class Solution 2 { 3 public: 4 vector<int> majorityElement(vector<int>& nums) 5 { 6 vector<int> res; 7 if (nums.empty()) return res; 8 // 初始化两个候选人candidate,和他们的计票 9 int cand1 = nums[0], count1 = 0; 10 int cand2 = nums[0], count2 = 0; 11 12 // 摩尔投票法,分为两个阶段:配对阶段和计数阶段 13 // 配对阶段 14 for (int num : nums) 15 { 16 // 投票 17 if (cand1 == num) 18 { 19 count1++; 20 continue; 21 } 22 if (cand2 == num) 23 { 24 count2++; 25 continue; 26 } 27 28 // 第1个候选人配对 29 if (count1 == 0) 30 { 31 cand1 = num; 32 count1++; 33 continue; 34 } 35 // 第2个候选人配对 36 if (count2 == 0) 37 { 38 cand2 = num; 39 count2++; 40 continue; 41 } 42 43 count1--; 44 count2--; 45 } 46 47 // 计数阶段 48 // 找到了两个候选人之后,需要确定票数是否满足大于 N/3 49 count1 = 0; 50 count2 = 0; 51 for (int num : nums) 52 { 53 if (cand1 == num) count1++; 54 else if (cand2 == num) count2++; 55 } 56 57 if (count1 > nums.size() / 3) res.push_back(cand1); 58 if (count2 > nums.size() / 3) res.push_back(cand2); 59 60 return res; 61 } 62 };
标签:for 大于 ++ cto else ack solution nbsp push
原文地址:https://www.cnblogs.com/yuhong1103/p/12684878.html