找“水王”
編程思路:
? ? ? 水王是發帖最多的人,如果用傳統的思想來遍歷去計數,計算每個id出現多少次再去比較固然能算出來,可是時間復雜度高。我們轉換思路重新分析這道題。
水王的特點為:(1)每貼必回(2)水王的發貼數超過總貼數的一半;
? ? 從頭開始遍歷,對可能成為水王的人的id進行計數,如果后邊的跟他相同就加一,不同就減一,如果為0就重新選擇水王。因為水王發的帖子大于一半,所以剩下的就是水王。
import java.util.Scanner; /** 尋找水王*/ public class ShuiWang {public static void main(String[] args) {int[] a = null;Scanner sc = new Scanner(System.in);System.out.println("帖子總個數:");int sum = sc.nextInt();a = new int[sum];System.out.println("輸入每個帖子的作者:");for(int i = 0;i < sum;i++){a[i] = sc.nextInt();}sc.close();int n = 0;int id = -1;for(int i=0;i<a.length;i++){if(n==0){id=a[i];n=2;}else{if(id==a[i]){++n;}else{--n;}}}System.out.println("水王的ID是 : " + id);}}程序執行結果:
?
?
總結:
要學會分析問題,發現“水王”的特點,轉換思考方式。
沒有實現隨機生成發帖的id。
轉載于:https://www.cnblogs.com/bai123/p/7010673.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
- 上一篇: WBS分析
- 下一篇: jmeter设置全局变量