您的位置:首页 > 其它

数组中出现次数超过一半的数字

2012-08-21 04:54 330 查看
问题:

给定一个 int 数组,找出里面出现次数超过一半的数字。

分析:

首先,我们假定该数组中存在超过一半的数字,要把那个数字找出来,我们有以下方法:

1. 排序。出现次数最大的那个数字一定是排序后第 n/2 + 1 那个值(假定是从1 开始数)。复杂度为O(nlgn).

2. 遍历一遍数组,找出数组里的最大值max和最小值min,然后创建一个大小为 max - min + 1的数组,把每一个出现的值所对应的位置加1。比如数组里最大值是1000,最小值是-100,那么我们创建一个1101大小的数组 A,如果原数组的值是50,我们就把 A[50 - (-100)] 的值 加 1。 这样,我们可以得到所有值出现的次数。但是,这样做的话,空间消耗有可能会特别大。复杂度为O(n)。

3.  本文算法:我们保存两个值,一个是value --- 当前出现次数最大的值, 一个是 count ---value出现的次数。我们遍历整个数组,如果遇到与value值相同的值,就把count 加1,否则减1。如果在做减法以前,count的值已经为0,就把那个不同的值设成value, count的值设成 1. 这样,我们保证能够找出出现次数超过一半的数字 value。

代码如下:

public int overHalf(int[] array) throws Exception {
//alert! array == null is different from array.length == 0
if (array == null || array.length == 0) {
throw new Exception("null array or the array has no element");
}

int value = array[0];
int count = 1;

for(int i = 1; i < array.length; i++) {
// the same
if (array[i] == value) {
count++;
}
//not the same
else {
//count is equal to 0
if (count == 0) {
value = array[i];
count = 1;
} else {
count--;
}
}
}

// check whether the array is valid
int total = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == value) total++;
}

if (total * 2 <= array.length) {
throw new Exception(" the array is not valid!");
}

return value;

}


转载请注明出处:http://blog.csdn.net/beiyeqingteng
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  exception null 算法