【leetcode】Majority Element (easy)(*^__^*)
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.
思路:
找主要元素,用major记录主要字母,n记录major相对于其他字母多出现的次数
if n == 0 , 设当前数字为主要数字
else if 当前数字等于主要数字, n++
else 当前数字不等于主要数字, n--
因为主要数字出现多于一半,所以最后major表示的一定是主要数字。
没测试就一次AC了
class Solution {
public:
int majorityElement(vector<int> &num) {
int major;
int n = ;
for(int i = ; i < num.size(); i++)
{
if(n == )
{
major = num[i]; n++;
}
else if(major == num[i])
{
n++;
}
else
{
n--;
}
}
return major;
}
};
随机推荐
- 常见web服务器错误
参考地址:http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.5 10 Status Code Definitions ...
- 数据结构与算法课程作业--1014. Translation
这道题思想很简单,就是用map将foreign的作为键值,english的值作为对应的映射值,然后通过直接用foreign作为map对象的下标直接查找. 本题比较烦人的一点就是输入数据,我使用了get ...
- Use XSLT in wix
Following content is directly reprinted from https://installpac.wordpress.com/2012/05/07/conflict-ma ...
- Css background缩写
例子: background:url(../images20130624/bg.png) no-repeat -1424px -5px; 官方API Value: ['background-color ...
- c语言结构体指针初始化
今天来讨论一下C中的内存管理. 记得上周在饭桌上和同事讨论C语言的崛起时,讲到了内存管理方面 我说所有指针使用前都必须初始化,结构体中的成员指针也是一样 有人反驳说,不是吧,以前做二叉树算法时,他的左 ...
- System Generator入门笔记
System Generator入门笔记 [CPLD/FPGA] 发布时间:2010-04-08 23:02:09 System Generator是Xilinx公司进行数字信号处理开发的一种设计 ...
- 添加远程链接MySQL的权限
mysql> grant 权限1,权限2,…权限n on 数据库名称.表名称 to 用户名@用户地址 identified by ‘连接口令’; 权限1,权限2,…权限n代表select,ins ...
- 用CSS实现Firefox 和IE 都支持的Alpha透明效果
有的时候,为了实现一些特殊效果,需要将页面元素变透明,本文介绍的就是用 CSS 实现 Firefox 和 IE 都支持的 Alpha 透明效果.CSS: filter:alpha(opacity=50 ...
- c#键盘鼠标钩子
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.W ...
- Global::pickSpecificClass_DNT
/*************************************************** Created Date: 13 Jul 2013 Created By: Jimmy Xie ...