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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Java代码:
class Solution {
public int majorityElement(int[] nums) {
int cnt = 1;
int res = nums[0];
for (int i = 1; i < nums.length; i++) {
if (cnt == 0) {
res = nums[i - 1];
cnt = 1;
}
if (nums[i] == res) {
cnt++;
}
else {
cnt--;
}
}
if (cnt > 0) {
return res;
}
else {
return nums[nums.length - 1];
}
}
}
public int majorityElement(int[] nums) {
int cnt = 1;
int res = nums[0];
for (int i = 1; i < nums.length; i++) {
if (cnt == 0) {
res = nums[i - 1];
cnt = 1;
}
if (nums[i] == res) {
cnt++;
}
else {
cnt--;
}
}
if (cnt > 0) {
return res;
}
else {
return nums[nums.length - 1];
}
}
}
本文介绍了一个寻找多数元素的算法实现,该算法能在给定数组中找到出现次数超过一半的元素。通过迭代计数的方式,算法能高效地找到多数元素。
2740

被折叠的 条评论
为什么被折叠?



