您的位置:首页 > 其它

169. Majority Element 难度:Easy 类别:分治

2016-09-11 11:06 393 查看
题目:

Given an array of size n, find the majority element. The majority element is the element that appears more than 
⌊
n/2 ⌋
 times.

You may assume that the array is non-empty and the majority element always exist in the array.

思路:

此题要求选出一个数组中出现次数最多的那一个数,可用分治算法的思想,将整个数组分成两个部分,先分别筛选出这两部分中出现次数最多的数,记为x和y,如果x等于y,则返回x,如果x不等于y,则x和y都是最终结果的候选,此时需要遍历整个链表考察x和y出现的次数,出现次数较多的就是最终返回的结果。复杂度T(n) = 2T(n/2) + O(n),所以T(n) = O(nlogn)。

程序:

int majorityElement(int* nums, int numsSize) {
if(numsSize == 0||numsSize == 1)
return *nums;

int x = majorityElement(nums,numsSize / 2);
int y = majorityElement(nums + numsSize / 2,numsSize - numsSize / 2);

if(x == y)
return x;

else
{
int countX = 0;
int countY = 0;

for(int i = 0;i < numsSize;i++)
{
if(*(nums + i) == x)
countX++;

else if(*(nums + i) == y)
countY++;
}

return countX > countY ? x : y;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: