剑指offer(28)—数组中出现次数超过一半的数字

原文地址:https://blog.csdn.net/CYF18120161685/article/details/77678411

题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。

思路
解法1:哈希表,保存每个数字的出现次数(value),取其中次数大于一半所对应的元素值(key)时间复杂度为O(n),空间复杂度为O(n)
解法2:若将数组排序,则排序后数组的中位数就是出现次数超过一半的数字,即长度为n的数组中第n/2大的数字,可将问题转化为求一个排序数组中第k大的数字的问题,利用快速排序的思想(先随机选择一个数,调整数组,使小于该数的都位于其左边,大于该数的都位于其右边再对左右分别重复操作,直至只剩下一个数),若选择的数所在位置正好为n/2,则return该数,若位置小于n/2,则中位数在其右侧,若大于n/2,则中位数在其左侧,典型的递归过程.

解法1:

#include "bintree.h"

#include<iostream>
#include <vector>
#include <map>


using namespace std;
    int MoreThanHalfNum_Solution(vector<int> numbers)
    {
        int n = numbers.size();
        map<int, int> m;   //map容器,记录每个元素出现的次数
            for (int i = 0; i < n; i++)
                {
                    m[numbers[i]]++;
                    if ( m[numbers[i]] > n/2)
                        return numbers[i];
                }
                return 0;
    }


int main()
{
    vector<int>vec={1,5,1,1,1,7,1,8};

    Print1Dvec(vec);

    int n=MoreThanHalfNum_Solution(vec  );
    Print1Dvec(vec);
    cout<<n<<endl;

       return 0;
}

解法2:

class Solution {
public:
    /****Partition函数重中之重,铭记于心****/
    int Partition(vector<int>& nums, int start, int end){
        int key = nums[start];
        while(start < end){
            while(start < end && nums[end] >= key)
                end--;
            swap(nums[start], nums[end]);
            while(start < end && nums[start] <= key)
                start++;
            swap(nums[start], nums[end]);
        }
        return start;
    }
    bool CheckMoreThanHalf(vector<int> nums, int key){
        int count = 0;
        for(int i = 0; i < nums.size(); i++){
            if(nums[i] == key)
                count++;
        }
        if(2 * count <= nums.size())
            return false;
        return true;
    }
    int MoreThanHalfNum_Solution(vector<int> numbers) {
        //解法2:快排,Partition函数
        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){    //index在start~mid中间,再检测index+1~end
                start = index + 1;
                index = Partition(numbers, start, end);
            }
            if(index > mid){    //index在mid~end中间,再检测start~index-1
                end = index - 1;
                index = Partition(numbers, start, end);
            }
        }
        int res = numbers[mid];
        if(!CheckMoreThanHalf(numbers, res))    //检测res是否出现次数超过len/2
            res = 0;
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/zhenaoxi1077/article/details/80457119