Niukewang Jianzhi offer simple question 3

More than half of the numbers in the array

topic:

There is a number in the array that appears more than half the length of the array. Please find out this number. For example, enter an array {1,2,3,2,2,2,5,4,2} of length 9. Since the number 2 appears 5 times in the array, which is more than half the length of the array, 2 is output. If it does not exist, output 0.

analysis:

First of all, the number required in the question needs to exceed the general length of the array, so it is the most in the array. We can first find the most number in the array, and then determine whether it exceeds half of the array,
set two counters 1 and 2, 1 Responsible for counting the number of occurrences of each number each time, 2 Responsible for saving the number that is more than the last time, setting a cache to save the current number of the largest number,
and comparing it with the last time after each statistics to determine whether Need to update counter 2 and cache.
The algorithm can be further optimized by sorting,

Code example

public static int search (int [] arr){
    
    
            Arrays.sort(arr);

            int len = arr.length;
            int other = 0;
            int large = 0;
            int count = 0;
            int j = 0;
            for (int i=0;i<len/2;i+=other){
    
    

                other =0;
               for (j=i;j<len;j++){
    
    
                   if (arr[i]==arr[j]){
    
    
                       other++;


                   }else {
    
    
                       break;
                   }
               }
               if (other>large){
    
    
                   large = other;
//                   other =0;
                   count=arr[i];
               }else {
    
    
                   continue;
               }

            }
            if (large > len/2){
    
    
                return count;
            }
            return 0;

    }

Guess you like

Origin blog.csdn.net/weixin_44712669/article/details/111302299