LeetCode 169. Majority Element - majority vote algorithm (Java)

1. 题目描述Description

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 exists in the array.

2. 思路Thoughts

• Initialize an element m and a counter i with i = 0
• For each element x of the input sequence:
• If i = 0, then assign m = x and i = 1
• else if m = x, then assign i = i + 1
• else assign i = i − 1
• Return m

a) 如果这两个字母包含A，例如删去A和C，那么$x = x - 1$, $y = y-1$, $x>y$依然成立因为$x-1>y-1 \ if \ x>y$。

b) 如果这两个字母都不包含A，例如删去B和D，那么$x$不变，$y=y-2$，$x>y$依然成立因为$x>y-2 \ if \ x > y$

3. 代码Code

class Solution {
public int majorityElement(int[] nums) {
int count = 1, current = nums[0];
for(int i = 1; i < nums.length; i++) {
if(count == 0) {
count++;
current = nums[i];
}
else if(current==nums[i])
count++;
else
count--;
}
return current;
}
}


posted @ 2017-12-12 09:27  rgvb178  阅读(...)  评论(...编辑  收藏