Java-- find water king

Design ideas:

Time complexity of O (n side) of the method is to obtain a number of occurrences of each ID, to obtain the largest one.

The time complexity of O (n side) approach is often thought king water ID appears must be greater than half. Therefore, the water will be continuously king of ID or out of the situation, either on the last one will be able to take advantage of this algorithm optimization.

Source:

package findwaterking;
public class Main {
 public static void find(int []list)
 {
  int l=list.length;
  int []sum=new int[l];
  for(int k=0;k<l;k++)
  {
   sum[k]=0;
  }
  for(int i=0;i<l;i++)
  {
   for(int j=0;j<l;j++)
   {
    if(list[i]==j)
    {
     sum[j]++;
    }
   }
  }
  int max=0;
  int flag=0;
  for(int m=0;m<l;m++)
  {
   if(sum[m]>max)
   {
    max=sum[m];
    flag=m;
   }
  }
  System.out.println("时间复杂度O(n方)得到的结果:"+flag);
 }
 static int findbetter public (int [] Array) 
    { 
        int size = be array.length; 
        int Result = 0; // results need to find 
        int times = 0; // number occurring 
        for (int i = 0; i <size; ++ I) 
        { 
            // if the number is equal to 0, the result reassign 
            IF (times == 0) 
            { 
                result = Array [I]; 
                times =. 1; 
            } 
            the else 
            { 
                IF (result == Array [I]) 
                { 
                    ++ times; 
                } 
                the else 
                { 
                    --times; 
                } 
            } 
        } 
        Return Result; 
    } 
 public static void main (String [] args) {
  // the TODO Auto-Generated Method Stub
  int [] = {1,2,1,3,1,4,1,1,1 List, } 1,1,3;
  Find (List);
  System.out.println ( "result time complexity O (n) is obtained:" + findbetter (List));
 }
}

Screenshot results:

to sum up:

Clarify the characteristics of the event, you can write for a more efficient algorithm.

Guess you like

Origin www.cnblogs.com/ruangongyouxi/p/11008460.html