This commit is contained in:
2026-07-23 16:56:50 +08:00
parent 124ad9afdf
commit 92784ffb0f
36 changed files with 2015 additions and 608 deletions
+47
View File
@@ -0,0 +1,47 @@
package top100liked
import (
"testing"
)
// https://leetcode.cn/problems/majority-element/?envType=study-plan-v2&envId=top-100-liked
// 169. 多数元素
//
// 给定一个大小为 `n` 的数组 `nums` ,返回其中的多数元素。多数元素是指在数组中出现次数 大于 `⌊ n/2 ⌋` 的元素。
// 你可以假设数组是非空的,并且给定的数组总是存在多数元素。
// 示例 1
// 输入:nums = [3,2,3]
// 输出:3
// 示例 2
// 输入:nums = [2,2,1,1,1,2,2]
// 输出:2
//
// 提示:
// - `n == nums.length`
// - `1 <= n <= 5 * 10^4`
// - `-10^9 <= nums[i] <= 10^9`
// - 输入保证数组中一定有一个多数元素。
// 进阶:尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。
//
func majorityElement(nums []int) int {
}
func TestMajorityElement(t *testing.T) {
cases := []struct {
name string
nums []int
want int
}{
{"example1", []int{3, 2, 3}, 3},
{"example2", []int{2, 2, 1, 1, 1, 2, 2}, 2},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got := majorityElement(c.nums)
if got != c.want {
t.Errorf("got %v, want %v", got, c.want)
}
})
}
}