Leetcode 169
来源:互联网 发布:游戏王网络对战平台 编辑:程序博客网 时间:2024/05/01 04:51
Leetcode 169, majority element, 难度 medium
因为这周正好在学分治,所以就做了这道分治的题目,就是不停地把数组分为两半,找到在这两半里面最多的元素,如果在这两半里面最多的元素相等,那这个就是majority,如果不等,那就遍历一边数组check是左边的元素多还是右边的元素多,返回多的元素,这里遍历用了容器里的count函数。
以下是代码:
class Solution {public: int majorityElement(vector<int>& nums) { return major1(nums, 0, nums.size() - 1); } int major1(vector<int>& nums, int begin, int end) { if(begin == end) return nums[begin]; if(begin < end) { int mid = begin + (end - begin) / 2; int left = major1(nums, begin, mid); int right = major1(nums, mid + 1, end); if(left == right) return left; else{ return count(nums.begin() + begin, nums.begin() + end + 1, left) < count(nums.begin() + begin, nums.begin() + end + 1, right) ? right : left; } } }};
阅读全文
0 0
- leetcode 169
- LEETCODE 169
- Leetcode 169
- leetcode 169
- leetcode 169
- Leetcode 169
- Leetcode note--Leetcode 169Majority Element
- LeetCode(169) Majority Number
- leetcode 169-Majority Element
- [leetcode 169] Majority Element
- leetCode#169 Majority Element
- leetCode 169 [PHP代码]
- Leetcode-169Majority Element
- LeetCode 169: Majority Element
- [LeetCode][169][Majority Element]
- LeetCode 169 Majority Element
- Majority Element leetcode[169]
- Leetcode[169]-Majority Element
- 人月神话读后总结
- 延迟加载配置
- Toolbar入门
- 搭建PHP开发环境(一)-Apache安装配置
- SSH关联映射注解
- Leetcode 169
- OkHttp面试相关知识
- matplotlib散点图,圆
- SSH缓存开启和配置
- 2017-9-14 笔试真题
- hdu 4462 Scaring the Birds # 暴力枚举(状压)
- UVA
- 设计模式-----工厂模式
- Mac下配置环境变量使用adb命令