LeetCode(169)Majority Element
2015-08-15 20:47
387 查看
题目
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.
分析
给定一个整数序列,求出其中出现次数大于floor(n/2)floor(n/2)的元素,并返回。这是一个很简单的题目,首先将序列排序,得到一个有序排列,然后依次遍历,统计重复元素的出现次数,返回次数大于一半的元素即可。
AC代码
class Solution { public: int majorityElement(vector<int>& nums) { //题目假设输入数组非空,且出现次数大于[n/2]的元素存在 int len = nums.size() , count = len/2; sort(nums.begin(), nums.end()); if (len == 1) return nums[0]; int tmp = 1; for (int i = 0; i < len-1; i++) { if (nums[i + 1] == nums[i]) { ++tmp; if (tmp > count) return nums[i]; } else{ tmp = 1; }//if }//for return -1; } };
GitHub测试程序源码
相关文章推荐
- poj 3264 & poj 3468(线段树)
- zoj 2672 Fibonacci Subsequence(hash + dp)
- 关于 Windows 8.1 虚拟光驱问题
- 数据结构 学习之图
- 测试对象销毁后指针是否还可以使用
- Codeforces Round #FF (Div. 2)
- 测试对象销毁后指针是否还可以使用
- LeetCode(169)Majority Element
- gulp实例
- Java功底篇系列-02-如何理解实际开发中与“排序”相关的问题
- UINavigationControl
- 【React】初识React
- JAVA注释
- 【快速判断素数,10^9】
- 触发器的学习
- 小小菜之Cocos2d-x游戏开发旅程——项目实例:贪吃蛇(3)
- 青岛Uber优步司机奖励政策(8/10-8/16)
- UVA 644 Immediate Decodability (字符处理)
- Hdu 1074 Doing Homework 状态压缩DP
- APM源码分析之 油门跟踪