0169. Majority Element

169. Majority Element #

Problem #

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.

Example 1:

Input: [3,2,3]
Output: 3

Example 2:

Input: [2,2,1,1,1,2,2]
Output: 2

Problem Summary #

Given an array of size n, find the majority element in it. The majority element refers to the element that appears more than ⌊ n/2 ⌋ times in the array. You may assume that the array is non-empty, and that the given array always has a majority element.

Solution Approach #

  • The problem requires finding the number that appears more than ⌊ n/2 ⌋ times in the array. The required space complexity is O(1). Easy problem.
  • The algorithm used in this problem is the Boyer-Moore Majority Vote Algorithm. https://www.zhihu.com/question/49973163/answer/235921864

Code #


package leetcode

// Solution 1 Time complexity O(n) Space complexity O(1)
func majorityElement(nums []int) int {
	res, count := nums[0], 0
	for i := 0; i < len(nums); i++ {
		if count == 0 {
			res, count = nums[i], 1
		} else {
			if nums[i] == res {
				count++
			} else {
				count--
			}
		}
	}
	return res
}

// Solution 2 Time complexity O(n) Space complexity O(n)
func majorityElement1(nums []int) int {
	m := make(map[int]int)
	for _, v := range nums {
		m[v]++
		if m[v] > len(nums)/2 {
			return v
		}
	}
	return 0
}



Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文