第一个简单的案例,一个家伙在论坛里每个人都回复了,其占所有帖子的总量超过了一半,快速找到这个ID
原文地址: http://www.java2000.net/p11239
/**
* 编程之美-寻找发帖"水王"。<br>
* 每个帖子均有回复,总发帖量超过一半了。找出这个人的ID.
*
* @author 赵学庆,Java世纪网(java2000.net)
*
*/
public class T {
/**
* 查找ID.
*
* @param id
* 所有帖子的作者ID
* @return
*/
public static int find(int[] id) {
int rtn = Integer.MIN_VALUE;
int nTimes, i;
for (i = nTimes = 0; i < id.length; i++) {
if (nTimes == 0) {
rtn = id[i];
nTimes = 1;
} else {
if (rtn == id[i]) {
nTimes++;
} else {
nTimes--;
}
}
}
return rtn;
}
public static void main(String[] args) {
int[] id = { 2, 3, 4, 5, 1, 2, 1, 3, 5, 7, 31, 3, 2, 2, 1, 12, 4, 56, 23, 12, 4, 1, 3, 4,
2, 2, 1, 3, 1, 23, 1, 5, 3, 1, 3, 12, 1, 2, 1, 1, 1, 2, 2, 2 };
System.out.println(find(id));
}
}
运行结果
1
提示:此问题的前提是一个ID的帖子量超过了一半,否则数据没有意义。