zoukankan      html  css  js  c++  java
  • LeetCode Distribute Candies

    原题链接在这里:https://leetcode.com/problems/distribute-candies/#/description

    题目:

    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: 3
    Explanation:
    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: 2
    Explanation: 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].

    题解:

    如果糖果中distinct 的标号个数 大于等于 candies数量的一半,那姐姐有办法能拿到糖果的标号都不同。否则就只能拿到distinct标号那么多的不同糖果.

    Time Complexity: O(candies.length).

    Space: O(candies.length.)

    AC Java:

     1 public class Solution {
     2     public int distributeCandies(int[] candies) {
     3         if(candies == null || candies.length == 0){
     4             return 0;
     5         }
     6         
     7         HashSet<Integer> hs = new HashSet<Integer>();
     8         for(int i : candies){
     9             hs.add(i);
    10         }
    11         
    12         return hs.size()>=candies.length/2 ? candies.length/2 : hs.size();
    13     }
    14 }
  • 相关阅读:
    vue使用Highcharts图表
    Laya 骨骼动画播放
    unity3d学习笔记
    unity学习笔记
    Laya本地存储对象,读取上来之后没有类方法了
    Laya2学习笔记
    Laya vscode f5断点调试开启
    fairyGUI学习笔记
    使用docker安装swoole环境
    docker学习笔记
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/7069558.html
Copyright © 2011-2022 走看看