1. 程式人生 > >陣列中找出出現次數超過一半的數

陣列中找出出現次數超過一半的數

劍指offer中的題目,利用快速排序的partition函式進行解決,程式碼如下

class Solution {
public:
    int partition(vector<int> numbers,int p,int r)
    {
        //當遇到特殊的輸入情況時候,要和麵試官溝通,究竟應該返回值取到什麼
        int x=numbers[r];
        int i=p-1;
        for(int k=p;k<r-1;k++)
        {
           if(numbers[k]<=x)
           {
               i+=1;
               swap(numbers[i],numbers[k]);
           }
        }
        swap(numbers[i+1],numbers[r]);
        return i+1;
    }
    bool ismorethanhalf(vector<int> numbers,int result)
    {
        bool res;
        int count=0;
        for(int i=0;i<numbers.size();i++)
        {
            if(numbers[i]==result)
                count++;
        }
        if(count*2<=numbers.size())
            res=false;
        else
            res=true;
        return res;
    }
    int MoreThanHalfNum_Solution(vector<int> numbers) {
        if(numbers.size()<=0)
            return 0;
        int len=numbers.size();
        int mid=len>>1;
        int start=0,end=len-1;
        int index=partition(numbers,start,end);
        while(index!=mid)
        {
            if(index>mid)
            {
                end=index-1;
                index=partition(numbers,start,end);
            }
            else{
                start=index+1;
                index=partition(numbers,start,end);
            }
        }
        if(ismorethanhalf(numbers,numbers[mid]))
        return numbers[mid];
        else
            return 0;
    }
};