We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
输入: [3,2,3] 输出: 3
输入: [2,2,1,1,1,2,2] 输出: 2
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/majority-element
如果肯定存在,那么那个元素的数量肯定大于长度的一半
func majorityElement(nums []int) int { l := len(nums) m := make(map[int]int, l) for i := 0; i < l; i++ { m[nums[i]]++ if m[nums[i]] > l/2 { return nums[i] } } return 0 }
如果肯定存在,那么排序之后中间的元素肯定是那个值
func majorityElement(nums []int) int { sort.Ints(nums) return nums[len(nums)/2] }
投票法,简单来说就是就是,设置两个变量,一个值value,和这个值出现的次数count。遍历数组,如果和这个值相等就count++,否则count--,当count为零,value也应该变,具体实现
func majorityElement(nums []int) int { value, count := nums[0], 0 for _, v := range nums { if count == 0 { value = v } if v == value { count++ } else { count-- } } return value }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
示例 2:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/majority-element
解答
哈希表
如果肯定存在,那么那个元素的数量肯定大于长度的一半
排序
如果肯定存在,那么排序之后中间的元素肯定是那个值
投票法
投票法,简单来说就是就是,设置两个变量,一个值value,和这个值出现的次数count。遍历数组,如果和这个值相等就count++,否则count--,当count为零,value也应该变,具体实现
The text was updated successfully, but these errors were encountered: