原文地址: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
寻找发帖"水王"的扩展问题,有3个ID,他们每个人的发帖量都超过了1/4,找到这3个新的"水王"
原文地址:http://www.java2000.net/p11241
[2, 1, 3]