您的位置:首页 > 其它

【Leetcode】Majority Element

2015-12-01 11:09 453 查看
题目链接:https://leetcode.com/problems/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.

思路:

考研的时候王道数据结构习题上有这题,求主元素,原来王道是从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];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: