题目链接:https://leetcode.com/problems/majority-element/
题目:
n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
You may assume that the array is non-empty and the majority element always exist in the array.
思路:
考研的时候王道数据结构习题上有这题,求主元素,原来王道是从leetcode抄的 = =
算法:
// 采用抵消的思路
public int majorityElement(int[] nums) {
int mje = 0, count = 0;
for (int i = 0; i < nums.length; i++) {
if (count == 0) {
mje = i;// count为0的时候,令当前值为主元素
count++;
} else { // 当前有候选主元素的时候
if (nums[mje] != nums[i]) {// 抵消非候选主元素
count--;
} else {
count++;
}
}
}
return nums[mje];
}