第二周:[LeetCode]169. Majority Element
来源:互联网 发布:mac怎么下载wps office 编辑:程序博客网 时间:2024/06/02 01:08
[LeetCode]169. Majority Element
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
方法一:分治法: 将数组拆成两半, 分别找出前一半的众数和后一半的众数,若这两个众数相等,则全局众数就为改数,若不相等,则出现次数较多的众数为全局众数。时间复杂度为T(n) = T(n/2) + 2n = O(n log n).
class Solution {public: int majorityElement(vector<int>& nums) { return divide_compare(nums,0,nums.size()-1); } int divide_compare(vector<int>& nums,int left,int right){ if (left == right) return nums[left]; int mid = left + (right - left)/2; int left_m = divide_compare(nums, left, mid); int right_m = divide_compare(nums, mid+1, right); if (left_m == right_m) return left_m; int left_m_count = count(nums.begin()+left,nums.begin()+right+1,left_m); int right_m_count = count(nums.begin()+left, nums.begin()+right+1, right_m); return left_m_count > right_m_count ? left_m: right_m; }};
方法二:Moore投票算法(相当于简单实现的分治法): 维护一个当前的候选众数和一个初始为0的计数器。遍历数组时,当前值为x,如果计数器是0, 将候选众数置为x,并将计数器加一,如果计数器非0, 若x与候选众数相等,计数器加1,否则计数器减1(相当于不同的数互相抵消)。遍历完数组后, 当前的候选众数就是所求众数。时间复杂度 = O(n)。
int majorityElement(vector<int>& nums) { int i,candidate=nums[0],count=1; for(i=1; i<nums.size();i++){ if(count == 0){ candidate = nums[i]; count++; continue; } if(candidate == nums[i]) count ++; else count --; } return candidate; }};
0 0
- 第二周:[LeetCode]169. Majority Element
- [LeetCode]169.Majority Element
- LeetCode 169.Majority Element
- 【LeetCode】169.Majority Element
- LeetCode 169. Majority Element
- LeetCode 169. Majority Element
- [leetcode] 169.Majority Element
- Leetcode 169. Majority Element
- 【LeetCode】169. Majority Element
- [LeetCode]169. Majority Element
- 169. Majority Element LeetCode
- LeetCode 169. Majority Element
- LeetCode 169. Majority Element
- Leetcode 169. Majority Element
- [LeetCode]169. Majority Element
- 【LeetCode】169. Majority Element
- leetcode 169. Majority Element
- leetcode 169. Majority Element
- 在使用CocoaPod的Xcode工程中断点没有调试信息的问题跟进
- 登陆界面用户名检测
- UVA
- Android 5.X之Ripple,Palette的详解
- C/C++编译器和基本库和常用工具(gcc系列)<亲测>
- 第二周:[LeetCode]169. Majority Element
- YOJ2281
- JS:js中获取一个无序列表并按照有序的方式显示
- 最小生成树(Prim算法)
- G将军
- rsyslog+mariadb+loganalyzer实现日志服务器搭建
- 把一个整数每个数位上的数累加,然后输出
- 使用Dev-C++查看vector数组中的变量值
- [CF555E]Case of Computer Network/[51NOD1470]计算机网络问题