169. 多数元素 golang

题目

  1. 多数元素
    给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 1:

输入: [3,2,3]
输出: 3
示例 2:

输入: [2,2,1,1,1,2,2]
输出: 2

解法

func majorityElement(nums []int) int {
	if len(nums) < 1 {
		return 0
	}

	count, flag := 1, nums[0]
	for i := 1; i < len(nums); i++ {
		if count < 1 {
			flag = nums[i]
			count = 1
			continue
		}
		if nums[i] == flag {
			count++
		} else {
			count--
		}
	}
	return flag
}
发布了356 篇原创文章 · 获赞 247 · 访问量 36万+

猜你喜欢

转载自blog.csdn.net/csdn_kou/article/details/104660464
今日推荐