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

来源:互联网 发布:php怎么防止sql注入 编辑:程序博客网 时间:2024/05/24 07:13

数组中出现次数超过一半的数字

题目描述

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为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:

class Solution {public:    int MoreThanHalfNum_Solution(vector<int> numbers) {        int len = numbers.size();        map<int, int> m;        int res = 0;        for(int i = 0; i < len; i++){            m[numbers[i]]++;            if(m[numbers[i]] > len/2)                res = numbers[i];        }        return res;    }};

解法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;    }};
阅读全文
0 0
原创粉丝点击