LeetCode Majority Element
来源:互联网 发布:office办公软件 编辑:程序博客网 时间:2024/06/01 19:59
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.
方法一 :分治
从中间分为两个子问题,分别对数组的左半部分和右半部分求解出现次数最多的数,分别得到lm和rm,如果lm == rm,则其就是出现次数最多的数,否则,lm和rm均是答案候选,比较二者在数组中的出现次数,多的就是我们要求的答案。代码如下:
class Solution {public: int majorityElement(vector<int>& nums) { return majEle(nums, 0, nums.size() - 1); }private: int majEle(vector<int>& nums, int left, int right){ //(1) if(left == right) return nums[left]; int mid = (left + right) / 2; int lm = majEle(nums, left, mid); int rm = majEle(nums, mid + 1, right); if(lm == rm) return lm; else //(2) return count(nums.begin() + left, nums.begin()+right + 1, lm) > count(nums.begin() + left, nums.begin()+right + 1, rm) ? lm : rm; }};
注意
- 注释(1)处如果不用引用参数传递会超时
- 注释(2)处count为c++ STL中algorithm头文件中的函数,作用为计数
0 0
- 【leetcode】Majority Element II,Majority element algorithm
- Leetcode: Majority Element &Majority Element II
- Leetcode Majority Element
- leetcode 169-Majority Element
- 【leetcode 哈希表】Majority Element
- LeetCode:Majority Element
- leetcode:Majority Element
- leetcode: Majority Element
- [LeetCode] Majority Element
- leetcode 153: Majority Element
- leetcode Majority Element
- LeetCode:Majority Element
- leetcode:Majority Element
- [LeetCode] Majority Element
- Leetcode-Majority Element
- [leetcode]Majority Element
- [LeetCode]Majority Element
- Leetcode: Majority Element
- JAVA 判断号码是手机还是固话
- [LeetCode18]4Sum
- swift UITableView(三)
- iOS修改UIWebView中的图片大小
- jquery(zepto) when then 使用
- LeetCode Majority Element
- Epoll
- ArcGIS教程:影响路径距离(水平系数)(二)
- swift UITableView(四)
- swift UITableView(五)
- Linux 格式化分区 报错Could not stat --- No such file or directory 和 partprobe 命令
- uva11997 K Smallest Sums
- 严重: Error configuring application listener of class org.springframework.web.context.ContextLoader
- UIButton的imageEdgeInsets和titleEdgeInsets属性 —— HERO博客