[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)
    }
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/ffcec7620230
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞