腾讯精选练习(3850) :求众数(LeedCode 169)

mac2022-06-30  29

题目

给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于⌊ n/2 ⌋的元素。

你可以假设数组是非空的,并且给定的数组总是存在众数。

示例 1:

输入: [3,2,3] 输出: 3

示例 2:

输入: [2,2,1,1,1,2,2] 输出: 2

代码实现

方法一:排序法

//Cpp class Solution { public: int majorityElement(vector<int>& nums) { sort(nums.begin(),nums.end()); int k = 1, n = nums.size(); int Ans = nums[0]; for(int i = 1; i < n; ++i) { if(nums[i] == nums[i-1]) { ++k; if(k > n / 2) break; } else { k = 1; Ans = nums[i]; } } return Ans; } };

方法二:摩尔投票法

//Cpp class Solution { public: int majorityElement(vector<int>& nums) { int count = 1, Ans = nums[0]; for(int i = 1; i < nums.size(); ++i) { if(nums[i] == Ans) ++count; else --count; if(count == 0) { ++i; Ans = nums[i]; ++count; } if(count > nums.size() / 2) break; } return Ans; } };

实验结果

方法一:排序法 执行结果:通过 执行用时 :24 ms, 在所有 C++ 提交中击败了78.77%的用户 内存消耗 :10.9 MB, 在所有 C++ 提交中击败了91.12%的用户

方法二:摩尔投票法 执行结果:通过 执行用时 :16 ms, 在所有 C++ 提交中击败了98.49%的用户 内存消耗 :10.8 MB, 在所有 C++ 提交中击败了97.00%的用户

最新回复(0)