LeetCode : Majority Element

来源:互联网 发布:2016淘宝双11成交额 编辑:程序博客网 时间:2024/05/23 18:56

思路1

数组经过快速排序,返回数组中间的值。超时。(直接使用sort函数会通过,而且比哈希表快)

void myQuickSort(vector<int>& nums, int begin, int end){    if(begin < end)    {        int l = begin, r = end;        int flag = nums[l];        while(l < r)        {            while(l < r && nums[r] >= flag)                r--;            nums[l] = nums[r];            while(l < r && nums[l] < flag)                l++;            nums[r] = nums[l];        }        nums[l] = flag;        myQuickSort(nums, begin, l - 1);        myQuickSort(nums, l + 1, end);    }}int majorityElement(vector<int>& nums){    int end = nums.size() - 1;    myQuickSort(nums, 0, end);    return nums[nums.size() / 2];}

思路2

使用哈希表记录。

int Solution::majorityElement(vector<int>& nums){    map<int, int> rec;    for(int i = 0; i < nums.size(); i++)    {        if(rec.find(nums[i]) != rec.end())            rec[nums[i]] ++;        else            rec[nums[i]] = 1;        if(rec[nums[i]] > nums.size() / 2)            return nums[i];    }    return -1;}
0 0
原创粉丝点击