More than half of the numbers appear in the array

Time limit: 1 second  Space limit: 32768K  Heat index: 127962
Knowledge points on this topic:  array
 Algorithm knowledge video explanation

Topic description

There is a number in the array that occurs more than half the length of the array, please find the number. For example enter an array of length 9 {1,2,3,2,2,2,5,4,2}. Since the number 2 appears in the array 5 times, which is more than half the length of the array, 2 is output. Output 0 if not present.
public class Solution {
    
   public void swap(int[] arr,int a,int b){
        int t = arr[a];
        arr[a] = arr[b];
        arr[b] = t;
    }
    public int Partition(int[] arr,int l,int r){
        int p = arr[l];//Set the sentinel position
        int i = l;
        int j = r;
        while (i < j){
            while (arr[j] >= p && i < j){
                j--;
            }
            if (i<j){
                swap(arr,i,j);
            }
            while (arr[i] <= p && i < j){
                i++;
            }
            if (i<j){
                swap(arr,i,j);
            }
        }
        return i;
    }
    public int MoreThanHalfNum_Solution(int[] arr) {
        if(arr.length == 0 || arr ==null)
            return 0 ;
        int l = 0 ;
        int r = arr.length-1;
        int mid = l + ((r-l)>>1);
        int index = Partition(arr,l,r);
        while(index != mid){
            if(index>mid){
                r = index-1;
                index = Partition(arr,l,r);
            }else{
                l = index+1;
                index = Partition(arr,l,r);
            }
        }
        int result = arr[mid];
        int count = 0;
        for(int i = 0 ;i<arr.length;i++){
            if(arr[i]==result)
                count++;
        }
        if(count*2<=arr.length)
            return 0;
        return  result;
    }
}
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326523083&siteId=291194637