Total Accepted: 96138
Total Submissions: 239623
Difficulty: Easy
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.
我的AC:
int comp(const int *a, const int *b){
if (*a >= *b)
return 1;
else
return -1;
}
int majorityElement(int* nums, int numsSize) {
qsort(nums, numsSize, sizeof(int), comp);
for (int i = 0; i < (numsSize + 1) / 2 ; i++){
if(nums[i] == nums[i + numsSize / 2])
return nums[i];
}
}
分析:
1、∵majority元素一定是出现过[n/2]次以上的 ∴排序后跟其之后n/2位的数进行比较即可。
2、不论numsSize的奇偶, i < (numsSize + 1) / 2 的循环终止,都时满足的。
【长度为9,数组下标0~8,循环最后一次是nums[4],nums[4 + 9/2]正好是末尾;
长度为10,数组下标0~9,循环最后一次是nums[4],nums[4 + 10/2]正好是末尾。】
本文介绍了一个简单的算法,用于从大小为n的数组中找到出现次数超过n/2的多数元素。该算法首先对数组进行排序,然后通过比较中间元素与其后的n/2位置的元素来确定多数元素。

2060

被折叠的 条评论
为什么被折叠?



