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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
题目大意:
有一个数组,求数组中的主要元素,主要元素的定义是:在数组中出现次数大于数组的一半,就是主要元素。题目保证主要元素存在,很明显,主要元素只能有一个。
思路:
- 两重循环,O(n2)
- 设置两个变量majority和count。majority始终记录主要元素并不断被更新,count记录该主要元素出现的次数。对于数组arr,假设当前遍历到arr[i],如果arr[i] == majority,则count加1,否则减1。当count小于0时,说明当前的majority数量太少了,都被其他元素抵消了,导致count小于0,此时更新majority和count的值。如果一个元素是majority,说明它的数量至少也得大于数组一半的数量,每出现一个不同的元素和它抵消,最后它至少剩余一个以上。
被Face++面试完虐后,决定多练C/C++
C代码:
#include <stdio.h>
int majorityElement(int* nums, int numsSize);
int main() {
int numsSize = 5;
int nums[5] = {10,9,9,10,1};
int result = majorityElement(nums, numsSize);
printf("%d", result);
return 0;
}
int majorityElement(int* nums, int numsSize) {
int majority = nums[0];
int count = 1;
for(int i = 1; i < numsSize; i++) {
if(nums[i] == majority) {
count++;
}else {
count--;
}
if(count < 0) {
majority = nums[i];
count = 1;
}
}
return majority;
}
算了,不勉强自己,还是附上java代码吧
class Solution {
public int majorityElement(int[] nums) {
int majority = nums[0];
int count = 1;
for(int i = 1; i < nums.length; i++) {
if(nums[i] == majority) {
count++;
}else {
count--;
}
if(count < 0) {
majority = nums[i];
count = 1;
}
}
return majority;
}
}