leetcode 575. Distribute Candies

来源:互联网 发布:淘宝装饰店铺教程 编辑:程序博客网 时间:2024/05/22 19:05

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:

  1. The length of the given array is in range [2, 10,000], and will be even.
  2. The number in given array is in range [-100,000, 100,000].
这个没啥好说的,非常简单,只要弄清楚思想就好了:数组长度为length,每个人分到length/2,如果能有(length/2的不同)就给(length/2的不同)给妹妹,如果没有(length/2的不同)就把(所有的不同)给妹妹。

import java.util.HashMap;import java.util.Map;public class Distribute_Candies_575 {public int distributeCandies(int[] candies) {Map<Integer, Integer> map=new HashMap<Integer, Integer>();int length=candies.length;int halfLength=length/2;int count=0;for(int i=0;i<candies.length;i++){int theCandy=candies[i];if(map.get(theCandy)==null){count++;map.put(theCandy, 0);}}if(count>halfLength){return halfLength;}else{return count;}}public static void main(String[] args) {// TODO Auto-generated method stubDistribute_Candies_575 d=new Distribute_Candies_575();int[] a=new int[]{1,1,2,3};System.out.println(d.distributeCandies(a));}}
不过这题看到大神的解答,貌似更适合用hashset??

public int distributeCandies(int[] candies) {    Set<Integer> set = new HashSet<>();    for(Integer candie : candies) {        set.add(candie);        if(set.size() == candies.length/2) return set.size();    }    return Math.min(set.size(), candies.length/2);}
HashSet类,是存在于java.util包中的类。同时也被称为集合,该容器中只能存储不重复的对象。


0 0
原创粉丝点击