The sword refers to offer-numbers that appear more than half of the times in the array

Method 1. Use the Partition function of quicksort

A number in the array appears more than half the length of the array. If I sort this array, the number in the middle of the array after sorting must be the number that appears more than half the time in the array. That is, this number is the statistical median, the n/2th number in an array of length n.
We have mature O(n) algorithms to get any Kth largest number in an array.

class Solution {
public:
 int Partition(vector<int> a, int l, int r)
    {
        int x=a[r];
        int i =l;
        for(int j=l; j<r;j++)
        {
            if(a[j]<x)
            {
                swap(a[i++],a[j]);
            }
        }
        swap(a[i],a[r]);
        return i;
    }
int MoreThanHalfNum_Solution(vector<int> numbers) 
    {
        int len= numbers.size();
        int mid = len/2;
        int l =0;
        int r =len-1;
        int index = Partition(numbers,l,r);
        while(mid!=index)
        {
            if(mid>index)
            {
                l = index+1;
                index= Partition(numbers,l,r);
            }
            else
            {
                r = index-1;
                index = Partition(numbers,l,r);
            }
        }
        int result = numbers[mid];
        int cnt =0;
        for(int i=0;i<len;i++)
        {
            if(numbers[i]==result)
                cnt++;
        }
        if(cnt*2<=len)
            return 0;
        return result;
    }
};

Method two, beating method

If the target number exceeds half the length of the array, remove two different numbers from the array at the same time, and the number left at the end is the number.
If there are two left, then these two are also the same, which is the result

class Solution {
public:
    int MoreThanHalfNum_Solution(vector<int> numbers) {
        int len = numbers.size();
        int result = numbers[0];
        int cnt=1;
        for(int i=0;i<len;i++)
        {
            if(cnt==0)
            {
                result =numbers[i];
                cnt =1;
            }
            else if(numbers[i]==result)
                cnt++;
            else
                cnt--;
        }
        int num =0;
        for(int i = 0;i<len;i++)
        {
            if(numbers[i]==result)num++;
        }
        if(num*2<=len)return 0;
        return result;
    }
};

Guess you like

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