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

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

题目

原题链接
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

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