剑指offer:数组中出现次数超过一半的数字
来源:互联网 发布:网络大电影票房 编辑:程序博客网 时间:2024/05/18 13:31
题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
//利用快排思想找到第middle大的数//还有更简单的办法:保存两个值,保存元素和次数//每次向后遍历若元素相同,次数加1,不相同减1//若次数为0,则设置下一个元素为新元素,次数设为1//则最后一个次数为1的值就是我们要找的值class Solution {public: int MoreThanHalfNum_Solution(vector<int> numbers) { int size = numbers.size(); if(0 == size) return 0; int middle = size>>1; //找到数组中的中位数复杂度O(n) int start = 0; int end = size - 1; int index = partition(numbers, start, end); while(index != middle) { if(index < middle) { start = index + 1; index = partition(numbers, start, end); } else if(index > middle) { end = index - 1; index = partition(numbers, start, end); } } //判断中位数是否超过了一半 int num = numbers[index]; int cout = 0; for(auto n:numbers) { if(n == num) cout++; } if(cout>(float)(size/2.0)) return num; else return 0; } //快排中的partition函数 int partition(vector<int> &numbers,int start, int end) { if(start == end) return start; int temp = numbers[end]; //跳出迭代的时候start = end while(start < end) { while(start < end && numbers[start] < temp) ++start; numbers[end] = numbers[start]; while(start < end && numbers[end] >= temp) --end; numbers[start] = numbers[end]; } numbers[end] = temp; return end; }};
0 0
- 剑指offer--数组中出现次数超过一半的数字
- 《剑指offer》数组中出现次数超过一半的数字
- 剑指offer:数组中出现次数超过一半的数字
- 【剑指Offer】数组中出现次数超过一半的数字
- 剑指offer:数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字||剑指offer
- 剑指offer 数组中出现次数超过一半的数字
- 剑指offer:数组中出现次数超过一半的数字
- [剑指offer]数组中出现次数超过一半的数字
- 《剑指offer》-数组中出现次数超过一半的数字
- 剑指offer|数组中出现次数超过一半的数字
- 剑指offer-数组中出现次数超过一半的数字
- 《剑指offer》数组中出现次数超过一半的数字
- 剑指offer - 数组中出现次数超过一半的数字
- 剑指Offer:数组中出现次数超过一半的数字
- 剑指offer-数组中出现次数超过一半的数字
- 剑指offer:数组中出现次数超过一半的数字
- 剑指offer 数组中出现次数超过一半的数字
- VS2015打开项目报错-已停止工作
- Tomcat8.0 Connector参数
- 最小费用最大流
- Linux 内存管理
- bzoj1040 [ZJOI2008]骑士
- 剑指offer:数组中出现次数超过一半的数字
- Freeline 的使用
- pat 1112. Stucked Keyboard
- 蓝桥杯 java 回形取数
- 用户余额充值、提现操作。
- Http协议概述
- 第一次的再坚持一下
- 浏览器中直接打开apk
- Conditional Random Fields as Recurrent Neural Networks