LeetCode|Majority Element *
2016-04-18 19:46
316 查看
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.
思路:
因为出现次数最多的数的数量比其他所有数的个数的和还多,所以遇见不同的两个数就丢弃。最后还能剩下来的就是数量最多的那个。
代码:
class Solution { public: int majorityElement(vector<int>& nums) { int res, num = 0; for (int i = 0; i < nums.size(); i++){ if(!num){ res = nums[i]; num = 1; } else if (res == nums[i]){ num++; } else { num--; } } return res; } };
Majority Element II
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.思路:
代码:
这里写代码片
相关文章推荐
- 不用工具就可以在虚拟机安好系统后,并只有c盘的情况下增加分区
- 图结构练习——最小生成树
- 第七周
- RBM/DBN训练中的explaining away概念
- Spring-Security
- Schema 创建表、删除表。往表里添加列,及添加列的常用类型及相应介绍。
- 判别训练的多尺度可变形部件模型 A Discriminatively Trained, Multiscale, Deformable Part Model
- UIScrollView 遇到的小坑
- Android webview实现上传图片的效果(图片压缩)
- 每天一种算法 - 冒泡排序
- Python Decorator 3: 嵌套
- arm交叉编译Valgrind
- valgrind,arm-linux交叉编译
- 转载内容
- arm-linux-gcc-4.3.2.tar.bz2 安装
- Windows平台下Git服务器搭建
- GridView(网络视图)的基本使用
- MAC上安装brew,安装wget
- Python学习笔记(六)——一些语句
- 保存页面全部图片的方法