[LeetCode By Go 7]575. Distribute Candies

题目

原题链接
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)
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,900评论 0 23
  • 山浮海上,西迤数里,琅齐亘古边陲。 白露夜来,霞光暮去,琴城肺腑帘锥。 仙境任鸾徊。 祥云覆绝顶,周野峨巍。 驾鹤...
    康小勇阅读 456评论 0 4
  • 确实如此。昨天的朋友圈里,一溜的都是这个话题。有给母亲送祝福的,有晒给母亲的礼物,有晒自己收到祝福的。 如今的节日...
    杨杨杨菇凉阅读 249评论 2 2
  • 知识需要融汇贯通,综合运用。既是复习,又是新尝试。合理分配图文所占比例,彼此照应,融为一体。 人物造型并非必须Q版...
    大路和小路阅读 942评论 1 4