169. Majority Element
2016-05-17 15:52
316 查看
169. Majority Element
Description: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.
Link:
https://leetcode.com/problems/majority-element/
Analysis:
这道题在《编程之美》的2.3寻找发帖“水王” 有出现,里边讲的很好。
对于ARRAY中的一个数K,确定其占到总数的一半以上,现在需要找出这个数K。
1.首先想到的方法肯定就是排序了,然后这个有序的ARRAY中第N/2项一定就是我们要找的数K。其时间复杂度为O(N*log2N+N)。
2.另外一种方法:对这个ARRAY每次删除两个不同的ID(不管是否包含要找的数K),那么剩下的ARRAY中,K出现的次数依然占总数的一半以上。下面证明一下:
删除前:n(K) >= N/2; 删除后:n(K) >= N/2 - 1; 此时K所占的比例:p(K) = n(K)/(N-2) >= (N/2 - 1)/(N-2) = 1/2
好,这样我们可以不断重复删数的过程,减小样本数,从而得到问题的答案。
Source Code(C++):
#include <iostream> #include <vector> #include <algorithm> using namespace std; /*************************先进行排序,取中位数*************************************/ /* class Solution { public: int majorityElement(vector<int>& nums) { sort(nums.begin(), nums.end()); return nums.at(nums.size()/2); } }; */ /*****************************不断减小样本数量的方法*************************************/ class Solution { public: int majorityElement(vector<int>& nums) { int candidate; int ncounts=0; for (int i=0; i<nums.size(); i++) { if (ncounts == 0) { candidate = nums.at(i); ncounts = 1; } else { if (candidate == nums.at(i)) { ncounts++; } else { ncounts--; } } } return candidate; } }; int main() { Solution sol; int a[5] = {1, 2, 3, 2, 2}; vector<int> v(5); for (int i=0; i<v.size(); i++) { v.at(i) = a[i]; } cout << sol.majorityElement(v); return 0; }
相关文章推荐
- iOS大文件分片上传和断点续传
- 【Android基础】webView设置背景图片
- R语言read.xlsx()解读
- 手动记录ubuntu终端的日志
- 原来这才是游戏上瘾的机制 如果把它用到生活中的话
- 第11周项目1—点—圆—圆柱类族的设计 (2)
- 构建之法阅读笔记06
- 适配器1
- 快速简化Android截屏工作
- ListView 初步了解
- iis发布后出现 .woff 404 (Not Found)的问题
- Hadoop的shell脚本分析
- okhttp3替代FormEncodingBuilder的方法
- 【软件测试】获取html页面中某个元素的XPath
- JVM中的垃圾收集器
- 从零开始学jQuery Validate 之01
- 查找列表中某个值的位置(python)
- 文章标题
- 欢迎使用CSDN-markdown编辑器
- 文章标题