您的位置:首页 > 其它

LeetCode : Majority Element

2016-09-29 20:50 309 查看

思路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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  快速排序 leetcode