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.length
1 <= n <= 5 * 104
-109 <= nums[i] <= 109
Follow-up: Could you solve the problem in linear time and in
O(1)
space?
class Solution:
def majorityElement(self, nums: List[int]) -> int:
cnt = m = 0
for v in nums:
if cnt == 0:
m, cnt = v, 1
else:
cnt += 1 if m == v else -1
return m
class Solution {
public int majorityElement(int[] nums) {
int cnt = 0, m = 0;
for (int v : nums) {
if (cnt == 0) {
m = v;
cnt = 1;
} else {
cnt += (m == v ? 1 : -1);
}
}
return m;
}
}
/**
* @param {number[]} nums
* @return {number}
*/
var majorityElement = function (nums) {
let cnt = 0,
m = 0;
for (const v of nums) {
if (cnt == 0) {
m = v;
cnt = 1;
} else {
cnt += m == v ? 1 : -1;
}
}
return m;
};
class Solution {
public:
int majorityElement(vector<int>& nums) {
int cnt = 0, m = 0;
for (int& v : nums) {
if (cnt == 0) {
m = v;
cnt = 1;
} else
cnt += (m == v ? 1 : -1);
}
return m;
}
};
public class Solution {
public int MajorityElement(int[] nums) {
int cnt = 0, m = 0;
foreach (int v in nums)
{
if (cnt == 0)
{
m = v;
cnt = 1;
}
else
{
cnt += m == v ? 1 : -1;
}
}
return m;
}
}
func majorityElement(nums []int) int {
cnt, m := 0, 0
for _, v := range nums {
if cnt == 0 {
m, cnt = v, 1
} else {
if m == v {
cnt++
} else {
cnt--
}
}
}
return m
}
impl Solution {
pub fn majority_element(nums: Vec<i32>) -> i32 {
let mut m = 0;
let mut cnt = 0;
for &v in nums.iter() {
if cnt == 0 {
m = v;
cnt = 1;
} else {
cnt += if m == v { 1 } else { -1 };
}
}
m
}
}