这是第 15 篇算法,力扣链接
仓库管理员以数组
stock
形式记录商品库存表。stock[i]
表示商品id
,可能存在重复。请返回库存表中数量大于stock.length / 2
的商品id
。示例 1:
输入: stock = [6, 1, 3, 1, 1, 1] 输出: 1
方法一:投票选举
这道题是标准的投票问题,如果某个数得到 stock.length / 2 票数就算最终结果。
func inventoryManagement(stock []int) int {
count, result := 0, stock[0]
for _, num := range stock {
if count == 0 {
result = num
}
if result == num {
count++
} else {
count--
}
}
return result
}
方法二:排序
与方法一同理,超过一半就会中选,那排序后的中位数一定可以当选。
func inventoryManagement(stock []int) int {
sort.Ints(stock)
return stock[len(stock) / 2]
}