您的位置:首页 > 其它

Leetcode 169.Majority Element

2017-09-10 18:01 405 查看
169. Majority Element

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.

对于这个题目,采用分治的方法。
一开始的想法是先使用桶排序,在用类似于快速排序的方法,把新的桶的数组进行切分,切到足够小时,用只剩两个值时作为边界,求出结果,这个算法的时间复杂度应该是O(n)。

后来发现,其实在用桶排序时,答案就是最大的桶的下标,徒增麻烦。而且对于测试样例的数据大小无法确定,用数组做桶也很麻烦。

后来想的办法是,把给的数组每次分为原来的一半,求每一半的主元素,分到足够小时,也就是数组只剩一个元素时作为边界,停止递归,在后续的判断两个主元到底哪个是大数组的主元时,通过比较在大的数组中,哪个候选值出现的次数多,作为大的数组主元,依次向上,最终得到结果。这个算法的时间复杂度应该是O(log n)。

class Solution {
public:
int majorityElement(vector<int>& nums) {
if (nums.size() == 1) return nums[0];
vector<int> subarray_one;
vector<int> subarray_two;

for (int i = 0; i < nums.size() / 2; i++) {
subarray_one.push_back(nums[i]);
}

for (int i = nums.size() / 2; i < nums.size(); i++) {
subarray_two.push_back(nums[i]);
}

int mElement_one;
int mElement_two;

mElement_one = majorityElement(subarray_one);
mElement_two = majorityElement(subarray_two);

int count_one = 0;
int count_two = 0;
for (int i = 0; i < nums.size(); i++) {
if (mElement_one == nums[i]) count_one++;
}
for (int i = 0; i < nums.size(); i++) {
if (mElement_two == nums[i]) count_two++;
}

if (mElement_one == mElement_two) return mElement_one;
else if (count_one > count_two) return mElement_one;
return mElement_two;
}
};


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