分享
  1. 首页
  2. 文章

[用Golang刷LeetCode之 7] 575. Distribute Candies

miltonsun · · 1063 次点击 · · 开始浏览
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

题目

原题链接
Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could gain.
Example 1:
Input: candies = [1,1,2,2,3,3]Output: 3Explanation:There are three different kinds of candies (1, 2 and 3), and two candies for each kind.Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too. The sister has three different kinds of candies.

Example 2:
Input: candies = [1,1,2,3]Output: 2Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1]. The sister has two different kinds of candies, the brother has only one kind of candies.

Note:
The length of the given array is in range [2, 10,000], and will be even.
The number in given array is in range [-100,000, 100,000].

题目大意: 给一个长度为偶数的整数数组,数组中不同数字都代表不同糖果,将糖果平均分给弟弟和妹妹,妹妹最多能得到几种糖果。

思路

记录糖果种类,若糖果种类大于数组的一半,妹妹最多得到candies.size()/2种糖果,否则每种糖果都可以得到

代码

distributeCandies.go

func distributeCandies(candies []int) int {
 var kinds int
 length := len(candies)
 kinds = length / 2
 var candiesMap map[int]int
 candiesMap = make(map[int]int)
 for _, v := range candies {
 _, ok := candiesMap[v]
 if !ok {
 candiesMap[v] = 1
 } else {
 candiesMap[v]++
 }
 }
 mapLen := len(candiesMap)
 if kinds > mapLen {
 kinds = mapLen
 }
 return kinds
}

测试

distributeCandies_test.go

package _575_Distribute_Candies
import "testing"
func TestDistributeCandies(t *testing.T) {
 candies1 := []int{1,1,2,2,3,3}
 kinds1 := DistributeCandies(candies1)
 want1 := 3
 if kinds1 != want1 {
 t.Errorf("fail, want %+v, get %+v\n", want1, kinds1)
 }
 candies2 := []int{1,1,2,3}
 kinds2 := DistributeCandies(candies2)
 want2 := 2
 if kinds2 != want2 {
 t.Errorf("fail, want %+v, get %+v\n", want2, kinds2)
 }
}

有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:miltonsun

查看原文:[用Golang刷LeetCode之 7] 575. Distribute Candies

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

关注微信
1063 次点击
暂无回复
添加一条新回复 (您需要 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)

给该专栏投稿 写篇新文章

每篇文章有总共有 5 次投稿机会

收入到我管理的专栏 新建专栏