找出数组中出现次数大于一半的数字 Java实现 剑指offer
来源:互联网 发布:seo网站推广服务 编辑:程序博客网 时间:2024/05/11 20:29
题目描述:
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0
解题思路:
第一种最简单,进行快速排序,然后取出最中间的数字,并且用这个数字遍历一遍数组,看看该数出现次数是不是大于数组长度的一半(实现代码如下,快速排序法);
第二种方法:思想:对数组同时去掉两个不同的数字,到最后剩下的一个数就是该数字。如果剩下两个,那么这两个也是一样的,就是结果);最终剩下的设两个数组下标索引(start,end,y一头一尾),比较下标出的元素,
若两个元素不一样,start--;end++;
若两个元素一样,end--;
最终会出现start与end相等或者end-start=1两种情况,对于前者,需要判断剩下的这个数字遍历一遍数组,看看该数出现次数是不是大于数组长度的一半;若是后者,直接比较两个数字是否相等,相等即返回该数字,不相等集返回0;
快速排序法:
public class Solution {
private int[] data;public int MoreThanHalfNum_Solution(int [] array) {
data=array;
startSort(0,data.length-1);
int key=data[(data.length-1)/2];
int count=0;
for(int i=0;i<data.length;i++){
if(data[i]==key){
count++;
}
}
if(count>(data.length)/2)
return key;
else
return 0;
}
public void startSort(int start,int end){
if(start>=end) return;
int index=partition(start,end);
startSort(start,index-1);
startSort(index+1,end);
}
public int partition(int start,int end){
int key=data[start];
while(start<end){
while(data[end]>=key&&start<end){
end--;
}
data[start]=data[end];
while(data[start]<=key&&start<end){
start++;
}
data[end]=data[start];
}
data[start]=key;
return start;
}
}
另一种方法:
public class Solution {
private int[] data;
public int MoreThanHalfNum_Solution(int [] array) {
data=array;
int result=0;
int start=0;
int end=array.length-1;
while(end-start>1){
if(array[start]!=array[end]){
end--;
start++;
}
else{
end--;
}
}
if(end-start==1){
if(array[start]==array[end]){
result=array[start];
}
}
else{
if(count(array[start])){
result=array[start];
}
}
return result;
}
public boolean count(int value){
boolean result=false;
int count=0;
for(int i=0;i<data.length;i++){
if(value==data[i])
count++;
}
if(count>((data.length)/2))
result=true;
return result;
}
}
- 找出数组中出现次数大于一半的数字 Java实现 剑指offer
- 剑指offer中找出出现次数超过一半的数字
- 剑指Offer面试题29:数组中出现次数超过一半的数字 Java实现
- 剑指Offer FindNumberMoreThanHalf 找出数组中出现次数超过一半的数字
- java实现找出数组中出现次数超过一半的数字
- 剑指offer--数组中出现次数超过一半的数字
- 《剑指offer》数组中出现次数超过一半的数字
- 剑指offer:数组中出现次数超过一半的数字
- 【剑指Offer】数组中出现次数超过一半的数字
- 剑指offer:数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字||剑指offer
- 剑指offer 数组中出现次数超过一半的数字
- 剑指offer:数组中出现次数超过一半的数字
- [剑指offer]数组中出现次数超过一半的数字
- 《剑指offer》-数组中出现次数超过一半的数字
- 剑指offer|数组中出现次数超过一半的数字
- 剑指offer-数组中出现次数超过一半的数字
- 《剑指offer》数组中出现次数超过一半的数字
- GO语言slice
- 递归思想:汉诺塔问题
- 关于tomcat支持软连接的设置
- Linux下编译安装redis,详细教程
- js基础篇四
- 找出数组中出现次数大于一半的数字 Java实现 剑指offer
- COGS 2274. [HEOI 2016] tree
- NSOperation的基本用法
- [BZOJ2734]集合选数
- map、set和unordered_map、unordered_set对比
- mapreduce过程
- Spark MLlib 入门学习笔记
- 【百度、腾讯、阿里等】+【JAVA开发实习生】+春招面试经验
- bzoj3702二叉树 线段树合并