169. Majority Element
2026/1/12大约 1 分钟约 326 字
169. Majority Element
难度: Easy
题目描述
Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.
Example 1:
Input: nums = [3,2,3] Output: 3
Example 2:
Input: nums = [2,2,1,1,1,2,2] Output: 2
Constraints:
n == nums.length1 <= n <= 5 * 104-109 <= nums[i] <= 109- The input is generated such that a majority element will exist in the array.
Follow-up: Could you solve the problem in linear time and in
O(1) space? 解题思路
代码实现
解决方案
java
class Solution {
public int majorityElement(int[] nums) {
//假设nums[0]是多数元素,用count=1 记录多数元素的数量
//遍历后面的元素,如果和多数元素相同 count++;如果不同count--;
//如果count==0时,重置多数元素为后一个元素,count==1;遍历完成后就可获得多数元素
int moreEle = nums[0];
int count = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] == moreEle) {
count++;
} else {
count--;
}
if (count == 0) {
moreEle = nums[i + 1];
count = 1;
i++;
}
}
return moreEle;
}
}