題目來源於 LeetCode 上第 169 號(Majority Element)問題,題目難度爲 Easy,AC率52.6%面試
題目地址: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.數組
給定一個數組,數組的長度爲n,找出數組中出現次數超過一半的元素bash
You may assume that the array is non-empty and the majority element always exist in the array.app
你能夠假設數組不爲空,且元素必定存在數組中post
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
複製代碼
採用的是摩爾投票算法,關於什麼是摩爾投票算法,能夠參考知乎這篇文章,戳這裏ui
算法效率以下: spa
class Solution {
public int majorityElement(int[] nums) {
int major = nums[0];
int count = 1;
for (int i = 1; i < nums.length; i++) {
if (count == 0) {
count = 1;
major = nums[i];
} else if (major == nums[i]) {
count++;
} else {
count--;
}
}
return major;
}
}
複製代碼