剑指offer29--数组中出现超过一半的数字
来源:互联网 发布:mac解压zip文件 编辑:程序博客网 时间:2024/04/29 22:11
public class MoreThanHalfNum {
/*
* 数组中有一个数字出现的次数超过数组长度的一般,求这个数字
*/
public Integer moreThanHalfNum(int[] array)
{
if(array==null)
return null;
Integer number=null;
int count=0;
Integer resultInteger=null;
for(int i=0;i<array.length;i++)
{
if(number==null)
{
number=array[i];
count++;
}
else
{
if(array[i]!=number)
if(count==0)
{
number=array[i];
count=1;
}
else
count--;
else
count++;
}
if(count==1)
resultInteger=number;
}
if(checkMoreThanHalf(array, resultInteger))
return resultInteger;
else
return null;
}
private boolean checkMoreThanHalf(int[] array,int number)
{
int times=0;
for(int i=0;i<array.length;i++)
{
if(array[i]==number)
times++;
}
if(times*2<=array.length)
return false;
else
return true;
}
}
/*
* 数组中有一个数字出现的次数超过数组长度的一般,求这个数字
*/
public Integer moreThanHalfNum(int[] array)
{
if(array==null)
return null;
Integer number=null;
int count=0;
Integer resultInteger=null;
for(int i=0;i<array.length;i++)
{
if(number==null)
{
number=array[i];
count++;
}
else
{
if(array[i]!=number)
if(count==0)
{
number=array[i];
count=1;
}
else
count--;
else
count++;
}
if(count==1)
resultInteger=number;
}
if(checkMoreThanHalf(array, resultInteger))
return resultInteger;
else
return null;
}
private boolean checkMoreThanHalf(int[] array,int number)
{
int times=0;
for(int i=0;i<array.length;i++)
{
if(array[i]==number)
times++;
}
if(times*2<=array.length)
return false;
else
return true;
}
}
0 0
- 剑指Offer29数组中出现次数超过一半的数字
- 剑指offer29--数组中出现超过一半的数字
- 剑指offer29:数组中出现次数超过一半的数字
- 剑指offer29:数组中出现次数超过一半的数字
- offer29--数组中出现次数超过一半的数字
- 剑指offer29题,牛客网中“数组中出现次数超过一半的数字”
- 【面试题】剑指offer29--数组中出现次数超过一半的数字
- 数组中出现超过一半的数字
- 剑指offer--数组中出现次数超过一半的数字
- 《剑指offer》数组中出现次数超过一半的数字
- 剑指offer:数组中出现次数超过一半的数字
- 【剑指Offer】数组中出现次数超过一半的数字
- 剑指offer:数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字||剑指offer
- 剑指offer 数组中出现次数超过一半的数字
- 剑指offer:数组中出现次数超过一半的数字
- [剑指offer]数组中出现次数超过一半的数字
- 《剑指offer》-数组中出现次数超过一半的数字
- 什么是项目管理[001]
- 快速删除选定区域数据
- JSP Learning -- JSP&EL(express language) studying Summary
- 关于java.lang.outofmemoryerror的报错处理
- VC皮肤库
- 剑指offer29--数组中出现超过一半的数字
- linux命令 od
- poj2186 Popular Cows 强联通
- 第十周项目三 统计血型
- mysql导入导出csv文件
- ERROR 2003 (HY000): Can't connect to MySQL server on 'xx.xx.xx.xx' (110)
- IOS数据持久化之Core Data(三) - 验证输入
- android 组件之 AlertDialog
- SIGGRAPH 2013 papers on the web