題目
原題鏈接
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].
題目大意: 給一個長度為偶數(shù)的整數(shù)數(shù)組纽竣,數(shù)組中不同數(shù)字都代表不同糖果秀菱,將糖果平均分給弟弟和妹妹,妹妹最多能得到幾種糖果税产。
思路
記錄糖果種類政钟,若糖果種類大于數(shù)組的一半归薛,妹妹最多得到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)
}
}