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]正好是末尾。】