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 }
  • 相关阅读:
    LeetCode 42. Trapping Rain Water
    LeetCode 209. Minimum Size Subarray Sum
    LeetCode 50. Pow(x, n)
    LeetCode 80. Remove Duplicates from Sorted Array II
    Window10 激活
    Premiere 关键帧缩放
    AE 「酷酷的藤」特效字幕制作方法
    51Talk第一天 培训系列1
    Premiere 视频转场
    Premiere 暴徒生活Thug Life
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/7069558.html
Copyright © 2011-2022 走看看