zoukankan      html  css  js  c++  java
  • [leetcode] 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: 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].

     分析:题目比较简单的,翻译一下就是:1、数组长度是偶数;2、将数组分成两个部分,每个部分元素个数相同;3、求使得某个部分数组元素种类最多的种类数。
          代码如下:
     1 class Solution {
     2    public int distributeCandies(int[] candies) {
     3         Arrays.sort(candies);
     4         int number = candies.length / 2;
     5         int cur_n = 1;
     6         for ( int i = 1 ; i < candies.length ; i ++ ){
     7             if ( candies[i] != candies[i-1] && cur_n < number ) cur_n++; 
     8         }
     9         return cur_n;
    10     }
    11 }

          运行时间68ms。这种方法刚开始我以为数组是有序的,结果有个案例过不了,发现测试中有无序的,所以加了一句排序代码。

          因为是无序的,所以考虑使用set。代码如下:

     1 class Solution {
     2     public int distributeCandies(int[] candies) {
     3         int number = candies.length / 2;
     4         Set<Integer> set = new HashSet<>();
     5         for ( int i = 0 ; i < candies.length ; i ++ ){
     6             if ( set.size() < number ) set.add(candies[i]);
     7         }
     8         return set.size();
     9     }
    10 }

          运行时间45ms。还是可以的。

     
  • 相关阅读:
    POJ 1509 Glass Beads【字符串最小表示法】
    Codeforces 665C Simple Strings【暴力,贪心】
    Codeforces 665D Simple Subset【构造】
    HDU 5667 Sequence【矩阵快速幂+费马小定理】
    Codeforces 667D World Tour【最短路+枚举】
    Codeforces 667D World Tour【最短路+枚举】
    HDU 5676 ztr loves lucky numbers【DFS】
    Codeforces 667C Reberland Linguistics【DFS】
    前端学习笔记三
    Datawhale编程——动态规划DP
  • 原文地址:https://www.cnblogs.com/boris1221/p/9304256.html
Copyright © 2011-2022 走看看