Majority Element
来源:互联网 发布:网络隔离变压器 编辑:程序博客网 时间:2024/06/05 16:26
这周做的还是分治算法的题目
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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
也是比较经典的,求一个数组中出现次数超过一半的数字。
参考了一个寻找发帖水王问题的帖子发帖水王
这个问题也主要思想也是以大化小,因为我们要找的数字在整个数组中出现次数超过一半,那么很容易得到,如果删去两个数字(不同时为我们要找的那个数字)时,这个数字出现的次数仍然是整个数组的一半。
所以方法就是,从第一个数字开始计算,记录其出现的次数,如果它后面一个数字和它不同,那么把次数归零,再从下一个数字开始计算,这样就相当于删去了前两个数字,成功地以大化小。
int majorityElement(vector<int>& nums) { int n, ntimes; n = nums[0]; ntimes = 1; for(int i = 1; i < nums.size(); i++) { if (n == nums[i]) { ntimes++; } else { if (ntimes = 0) { n = nums[i]; ntimes = 1; } else { ntimes--; } } } return n; }
阅读全文
0 0
- majority element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- Majority Element
- majority element
- Majority Element
- Majority Element
- 搜索引擎solr系列---solr介绍(待扩充)
- JAVA中实现对Excel的导入与导出
- matlab安装
- git 的配置在哪
- leetcode------第一题 Two Sum
- Majority Element
- Tensorflow 实战 笔记
- 树的高度,深度,层数
- 强化学习基础学习系列之强化学习简介
- Oracle数据库--表锁的情况查询
- [ 工作--管理]-------项目管理软技术
- 寻向所志大学生
- Java 集合框架-Map
- Java概述