《剑指offer》数组中出现次数超过一半的数字
2016-07-19 20:43
465 查看
一、题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。二、输入描述
输入一个数组三、输出描述
超过数组长度的一半的数,如果没有输出0四、牛客网提供的框架
class Solution { public: int MoreThanHalfNum_Solution(vector<int> numbers) { } };
五、解题思路
这是2013年腾讯招聘题目。以下是《王道求职宝典》的方法:1)初始化:设当前的数组为data[],数组的长度为n。currentAxis=data[0],currentNum=1;
2)设i=1,遍历数组,转向3;
3)当data[i]==currentNum==0时,currentNum++,转向5;否则转向4;
4)currentNum–,当currentNum==0时,currentAxis=data[i];
5)当i==data.length时,转向(6);否则i++,转向3;
6)再次遍历数组中值为currentAxis的个数是否超过数组长度的一半;转向7;
7)如果是输出currentAxis,否则输出0;
六、代码
#include<iostream> #include<vector> using namespace std; class Solution { public: int MoreThanHalfNum_Solution(vector<int> numbers) { if(numbers.size() < 1) return 0; if(numbers.size() == 1) return numbers[0]; int numCount = 1; int temp = numbers[0]; for(int i = 1; i < numbers.size(); i++) { if(numCount <= 0){temp = numbers[i]; numCount = 1;} if(numbers[i] == temp) numCount++; else numCount--; } int num = 0; //检查值为temp的个数是否超过数组长度的一半 for(int i = 0; i < numbers.size(); i++) { if(numbers[i] == temp) num++; } if(numCount > 0 && num > numbers.size()/2) return temp; else return 0; } };
相关文章推荐
- 用angular把页面中的元素按照页面分离开
- angular用ng-repeat批量处理数据
- 《剑指offer》字符串的排列
- JavaScript基础知识整理
- angular的切换页面
- 回看JSP——解决提交form表单出现的乱码问题
- JSP注释格式
- HTML5编辑API之Range对象
- PHP文件数据传输用jQuery-ajax进行浏览器->服务器->数据文件->服务器->浏览器的数据传输($_POST,$_GET,json_encode(数组数据回应),json数据解析)
- yeoman-bower-grunt之间的关系
- fck实现htm在线编辑
- js实现ajax
- [Leetcode]289. Game of Life
- child伪类选择符入门(2)
- iOS之 改变日期显示样式
- 一个初级的前端工程师需要知道些什么?
- Nodejs从有门道无门菜鸟起飞教程。
- 基于ntkoocx.js的在线word编辑
- CSS,font-family,好看常用的中文字体
- 《剑指offer》二叉搜索树与双向链表