Since the ID number of the water King appeared more than half of the total number of the ID, the ID is different every two adjacent cancellation, must be the last remaining water ID king
Package main; Import java.util.Scanner; public class zhuti { static Scanner in = new new Scanner (the System.in); static int ID = 0 ; static int COUNT = 0 ; public static void main (String [] args) { int n-; int [] = ARR new new int [10 ]; System.out.println ( "Please enter the total number of posts:" ); n- = in.nextInt (); System.out.println ( "Please enter each water Army ID: "); for(int i=0;i<n;i++) { arr[i]=in.nextInt(); } findid(arr,n); System.out.println("水王的ID是:"+id); } static void findid(int arr[],int n) { for (int i=0;i<n;i++) { if (count==0) { count++; id=arr[i]; } else { if(id==arr[i]) count++; else count--; } } } }
As long as the problem has been appropriate and decomposition method, it will become very simple.