zoukankan      html  css  js  c++  java
  • 找水王

        三人行设计了一个灌水论坛。信息学院的学生都喜欢在上面交流灌水,传说在论坛上有一个“水王”,他不但喜欢发帖,还会回复其他ID发的每个帖子。坊间风闻该“水王”发帖数目超过了帖子数目的一半。

    如果你有一张当前论坛的帖子(包括回帖)列表,其中帖子的作者的ID也在其中,你能快速的找到这个传说中的水王吗?

         设计思想:因为“水王”发帖数超过了一半,将相邻两两不同的ID消除,则剩下的为“水王”的ID。用一个一维数组a[]存储所有ID,令“水王”ID为数组中的第一个a[0],用一个整型j记录水王ID出现次数,相邻数比较相同则j++,不同则j- -,并且如果j<=0,则对水王换ID,进行循环判断,直至循环结束。

     package main;
     import java.util.*;
     
     public class Item {
    
        public static void main(String[] args) {
             // TODO Auto-generated method stub
          Find_function function = new Find_function();
             Scanner sca=new Scanner(System.in);
            System.out.println("输入帖子数:");
             int n=sca.nextInt();
             String post[]=new String[n+1];
    
             int i;
             System.out.println("输入帖子ID:");
             for(i=0;i<n+1;i++)
          {
                   post[i]=sca.nextLine();
            }
            String shuiwang = function.find(post, n);
            System.out.println("水王ID是 " + shuiwang);
         }
    
       
     }
     class Find_function {
         String find(String[] post,int n)
          {
             int i,j = 0;
                  String shuiwang = post[0];//令第一个ID为水王
                  for(i=0;i<n;i++)
                  {
                       if(!shuiwang.equals(post[i]))
                     {
                          j=j-1;
                          if(j<=0)    //如果j=0时,之前的ID一定有一半以上不是水王,所以消去的至多有一半水王
                             {
                                shuiwang=post[i+1];    //在剩下的ID中继续寻找
                                  j=1;        //重新定义水王ID出现次数
                                    i++;
                                }
                         }
                     else
                           {
                              shuiwang=post[i];
                              j=j+1;//水王帖子数
                       }
                  }
                  return shuiwang;
          }
           }

    个人总结:当一个问题出现时 我们可以用简单的 删除思想来解决  

    无关的数据删除 需要的保留

  • 相关阅读:
    免费的数据库建模工具
    [原创]程序设计 异常处理总结
    C#混淆器 xenocode 使用说明
    [转载]Quartz.net官方开发指南 第九课: JobStore
    [转载] Quartz Cron 表达式(时间格式的写法)
    calico+macvlan
    华为欧拉openEuler 更新源没有main路径
    Difference between "genmask" and "netmask"?
    left join、right join和join的区别
    SQL查询时根据类型条件转换
  • 原文地址:https://www.cnblogs.com/1983185414xpl/p/10999916.html
Copyright © 2011-2022 走看看