题目来源于 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;
}
}
复制代码